简体   繁体   中英

How to automatically uncheck checkbox if textbox is filled

I've made the checkbox to be default check. How can I uncheck the checkbox automatically if certain textfield is filled. I've thinking of using javascript.


I tried using this

<input type="text" name="commentID" id="commentID" onkeyup="userTyped('skipID', this)"/>
<input type="checkbox" name="skipID" value="N" id="skipID" checked="checked"  />

and the javascript

function userTyped(commen, e){
if(e.value.length > 0){
    document.getElementById(commen).checked=false;
}else{
    document.getElementById(commen).checked=true;
}}​

It works but how if i have 3 textfield, and I want the checkbox to be filled only after all textfield is filled.

Just do this:

<input type="checkbox" id="someid" checked="checked"/>

<textarea onchange="if (this.value != '') document.getElementById('someid').checked = false;"></textarea>
 if(document.getElementById('yourtextBox').value!=' ')
 {
    document.getElementById('checbox').checked=false;
 } 

Try the following code. In this code, each time when you type a character in the textfield, the function will be called and the length of the textfield value is not zero, the checbox will be unchecked and it will be checked while you clear your textfield

//Function get called when you type each letter
function OnChangeTextField(){
    //getting the length of your textbox
    var myLength = $("#myTextbox").val().length;
    if(myLength > 0){
        $("#myCheckbox").attr("checked", false);
    }else{
           $("#myCheckbox").attr("checked", true);
        }

}


<input type = "text" id = "myTextbox" onkeyup= "OnChangeTextField();"/>
<input type="checkbox" id = "myCheckbox" value = "true" checked = "checked"/>
$("#comment").on("keyup blur", function () {
    $("#box").prop("checked", this.value == "");
});

EDIT: You can also use jQuery

 $("#comment").on("keyup blur", function() {
    $("#box").prop("checked", this.value == "");
});

Try jQuery, This works for me...

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.

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