I am trying to validate "mytextinput" only if the checkbox with the id="checkbox" is checked. No luck! Tried these variations of script:
if (myform.mytextinput.value=="" && document.getElementById("checkbox").checked) {
alert ('Please enter something!');
return false;}
if (myform.mytextinput.value=="" && document.getElementById("checkbox").checked==true) {
alert ('Please enter something!');
return false;}
if (myform.mytextinput.value=="" || document.getElementById("checkbox").checked) {
alert ('Please enter something!');
return false;}
What am I doing wrong?
You could make it this way. The validation of your input will only executed if your checkbox is checked.
if(document.getElementById("checkbox").checked){
if (myform.mytextinput.value == "") {
alert("Please enter something!");
return false;
}
//... more validation
}
In your solution you're validating the checkbox AND your input but possibly it's not necessary to check the input because the checkbox isn't checked.
If you want the users to write something in the textfield, but only validate if the checkbox with id checkbox
is checked, this should work:
if (myform.mytextinput.value.length < 1 && document.getElementById("checkbox").checked) {
alert ('Please enter something!');
return false;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.