简体   繁体   English

基本验证/复选框和文本字段

[英]Basic validation / checkbox and text field

I am trying to validate "mytextinput" only if the checkbox with the id="checkbox" is checked. 我只是在选中id =“checkbox”的复选框时才尝试验证“mytextinput”。 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. 在您的解决方案中,您正在验证复选框和输入,但可能没有必要检查输入,因为未选中复选框。

JSfiddle 的jsfiddle

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: 如果您希望用户在文本字段中写入内容,但仅验证是否选中了带有id checkbox ,则此操作应该有效:

if (myform.mytextinput.value.length < 1 && document.getElementById("checkbox").checked) {
    alert ('Please enter something!');
    return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM