빈 입력 필드에 대한 JavaScript 유효성 검사
인사말, <input name="question"/>
제출 버튼을 클릭하여 제출할 때 IsEmpty 함수를 호출하고 싶은 입력 필드가 있습니다.
아래 코드를 시도했지만 작동하지 않았습니다. 어떤 충고?!
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=unicode" />
<meta content="CoffeeCup HTML Editor (www.coffeecup.com)" name="generator" />
</head>
<body>
<script language="Javascript">
function IsEmpty() {
if (document.form.question.value == "") {
alert("empty");
}
return;
}
</script>
Question: <input name="question" /> <br/>
<input id="insert" onclick="IsEmpty();" type="submit" value="Add Question" />
</body>
</html>
<script type="text/javascript">
function validateForm() {
var a = document.forms["Form"]["answer_a"].value;
var b = document.forms["Form"]["answer_b"].value;
var c = document.forms["Form"]["answer_c"].value;
var d = document.forms["Form"]["answer_d"].value;
if (a == null || a == "", b == null || b == "", c == null || c == "", d == null || d == "") {
alert("Please Fill All Required Field");
return false;
}
}
</script>
<form method="post" name="Form" onsubmit="return validateForm()" action="">
<textarea cols="30" rows="2" name="answer_a" id="a"></textarea>
<textarea cols="30" rows="2" name="answer_b" id="b"></textarea>
<textarea cols="30" rows="2" name="answer_c" id="c"></textarea>
<textarea cols="30" rows="2" name="answer_d" id="d"></textarea>
</form>
여기에서 작동 예를 참조하십시오.
필수 <form>
요소 가 누락되었습니다 . 코드는 다음과 같습니다.
function IsEmpty() {
if (document.forms['frm'].question.value === "") {
alert("empty");
return false;
}
return true;
}
<form name="frm">
Question: <input name="question" /> <br />
<input id="insert" onclick="return IsEmpty();" type="submit" value="Add Question" />
</form>
입력 필드 에는 공백이있을 수 있으므로 다음을 방지합니다.
function isEmpty(str){
return !str.replace(/\s+/, '').length;
}
예:
function isEmpty(str){
return !str.replace(/\s+/, '').length;
}
document.getElementById("name").addEventListener("input", function() {
if( isEmpty(this.value) ) {
console.log( "NAME IS EMPTY!" )
}
});
<input id="name" type="text">
사용자가 자바 스크립트를 비활성화 한 경우 필수 속성을 추가하고 싶습니다.
<input type="text" id="textbox" required/>
모든 최신 브라우저에서 작동합니다.
if(document.getElementById("question").value.length == 0)
{
alert("empty")
}
입력 요소에 ID "질문"을 추가 한 후 다음을 시도하십시오.
if( document.getElementById('question').value === '' ){
alert('empty');
}
현재 코드가 작동하지 않는 이유는 거기에 FORM 태그가 없기 때문입니다. 또한 "이름"을 사용한 조회는 더 이상 사용되지 않으므로 권장되지 않습니다.
See @Paul Dixon's answer in this post : Is the 'name' attribute considered outdated for <a> anchor tags?
if(document.getElementById("question").value == "")
{
alert("empty")
}
Just add an ID tag to the input element... ie:
and check the value of the element in you javascript:
document.getElementById("question").value
Oh ya, get get firefox/firebug. It's the only way to do javascript.
My solution below is in es6 because I made use of const
if you prefer es5 you can replace all const
with var
.
const str = " Hello World! ";
// const str = " ";
checkForWhiteSpaces(str);
function checkForWhiteSpaces(args) {
const trimmedString = args.trim().length;
console.log(checkStringLength(trimmedString))
return checkStringLength(trimmedString)
}
// If the browser doesn't support the trim function
// you can make use of the regular expression below
checkForWhiteSpaces2(str);
function checkForWhiteSpaces2(args) {
const trimmedString = args.replace(/^\s+|\s+$/gm, '').length;
console.log(checkStringLength(trimmedString))
return checkStringLength(trimmedString)
}
function checkStringLength(args) {
return args > 0 ? "not empty" : "empty string";
}
<pre>
<form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name" />
<input type="submit"/>
</form>
</pre>
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("myform");
frmvalidator.EnableFocusOnError(false);
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name", "req", "Plese Enter Name");
</script>
before using above code you have to add the gen_validatorv31.js file
참고URL : https://stackoverflow.com/questions/3937513/javascript-validation-for-empty-input-field
'your programing' 카테고리의 다른 글
': app @ debug / compileClasspath'에 대한 종속성을 해결할 수 없음 : com.android.support:appcompat-v7:26.1.0을 확인할 수 없습니다. (0) | 2020.10.04 |
---|---|
Windows에서 어셈블러로 Hello World를 작성하는 방법은 무엇입니까? (0) | 2020.10.04 |
Ruby에서 UTC 타임 스탬프를 ISO 8601로 변환 (0) | 2020.10.04 |
모든 Flask 경로에 접두사 추가 (0) | 2020.10.04 |
React component / div를 드래그 가능하게 만드는 권장 방법 (0) | 2020.10.04 |