Mam to pole wejściowe,
<input name="question"/>
które chcę wywołać funkcję IsEmpty po przesłaniu, klikając przycisk przesyłania.
Wypróbowałem poniższy kod, ale nie zadziałał. jakakolwiek rada?
<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>
javascript
Eyla
źródło
źródło
return false
... itd. Itd.Odpowiedzi:
<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>
źródło
if
instrukcji spowodują zwrócenie tylko ostatniego czeku: stackoverflow.com/a/5348007/713874Zobacz przykład roboczy tutaj
Brakuje wymaganego
<form>
elementu. Oto jak powinien wyglądać Twój kod: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>
źródło
Pole wejściowe może zawierać spacje , chcemy temu zapobiec.
Użyj String.prototype.trim () :
function isEmpty(str) { return !str.trim().length; }
Przykład:
const isEmpty = str => !str.trim().length; document.getElementById("name").addEventListener("input", function() { if( isEmpty(this.value) ) { console.log( "NAME is invalid (Empty)" ) } else { console.log( `NAME value is: ${this.value}` ); } });
<input id="name" type="text">
źródło
Chciałbym dodać wymagany atrybut na wypadek wyłączenia javascript przez użytkownika:
<input type="text" id="textbox" required/>
Działa na wszystkich nowoczesnych przeglądarkach.
źródło
if(document.getElementById("question").value.length == 0) { alert("empty") }
źródło
Dodaj identyfikator „pytanie” do elementu wejściowego, a następnie spróbuj tego:
if( document.getElementById('question').value === '' ){ alert('empty'); }
Twój obecny kod nie działa, ponieważ nie masz w nim tagu FORM. Ponadto wyszukiwanie przy użyciu „nazwy” nie jest zalecane, ponieważ jest przestarzałe.
Zobacz odpowiedź @Paul Dixon w tym poście: Czy atrybut „name” jest uważany za nieaktualny dla <a> tagów kotwicy?
źródło
if(document.getElementById("question").value == "") { alert("empty") }
źródło
<input>
elemencie; działałoby to tylko w IE, ponieważ IE jest uszkodzony.Po prostu dodaj identyfikator do elementu wejściowego ... tj .:
i sprawdź wartość elementu w swoim javascript:
document.getElementById ("pytanie"). wartość
O tak, pobierz firefox / firebug. To jedyny sposób na wykonanie javascript.
źródło
Poniżej moje rozwiązanie jest w ES6 bo wykorzystały
const
jeśli wolisz ES5 można zastąpić wszystkoconst
zvar
.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"; }
źródło
<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>
przed użyciem powyższego kodu musisz dodać plik gen_validatorv31.js
źródło
Łącząc wszystkie podejścia, możemy zrobić coś takiego:
const checkEmpty = document.querySelector('#checkIt'); checkEmpty.addEventListener('input', function () { if (checkEmpty.value && // if exist AND checkEmpty.value.length > 0 && // if value have one charecter at least checkEmpty.value.trim().length > 0 // if value is not just spaces ) { console.log('value is: '+checkEmpty.value);} else {console.log('No value'); } });
<input type="text" id="checkIt" required />
Zauważ, że jeśli naprawdę chcesz sprawdzić wartości, powinieneś to zrobić na serwerze, ale to jest poza zakresem tego pytania.
źródło
Możesz przejrzeć każde wejście po przesłaniu i sprawdzić, czy jest puste
let form = document.getElementById('yourform'); form.addEventListener("submit", function(e){ // event into anonymous function let ver = true; e.preventDefault(); //Prevent submit event from refreshing the page e.target.forEach(input => { // input is just a variable name, e.target is the form element if(input.length < 1){ // here you're looping through each input of the form and checking its length ver = false; } }); if(!ver){ return false; }else{ //continue what you were doing :) } })
źródło
<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>
źródło