Skip to content
Advertisement

how to disable a check box using java script conditionally

i have 3 check boxes in 3 different pages,i want to check one check box at time means at first all 3 are unchecked and if i checked one check box remaining 2 check boxes should be disable.

each check box value i am storing in 3 different text file using array in the form of 1’s and 0’s. now for one page i am reading check box values and based condition trying to disable check box but its not working.

I have Tried this

check box html code:

input type="checkbox" id="cb1" name="check[0]" value="1" />

java script:

<script type="text/javascript">

var cb1 =document.getElementById("cb1");
var cb2 = "<?php echo $cb2_arr[5] ?>" ; //cb2=1 or 0
var cb3 = "<?php echo $cb3_arr[6] ?>"; //cb3=1 or 0

if(cb2 ==1 || cb3 == 1){
cb1.disabled = true;
}else{
cb1.disabled = false;
}
</script>

cb1.disabled = true; for me its not working i kept alert statements above and below it ,only above one is displayed

Please help me how to set disabled property, thanks

Advertisement

Answer

You need to check input1.value == "", not simply input1 == ""

You also need to fire your method originally, and also run it every time your select lists change value.

Give the function a name

function setCheckState(evt) {
    if (input1.value == "" || input2.value == "") {
        result.disabled = true;
    } else {
        result.disabled = false;
    }
}

Add event listeners

input1.addEventListener('change', setCheckState);
input2.addEventListener('change', setCheckState);
// Fire the method to get the initial checkbox state set

setCheckState();

Finally, you can reduce your if() statement to a simple assignment…

function setCheckState(evt) {
    result.disabled = input1.value == "" || input2.value == "";
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement