简体   繁体   中英

Disable button using checkbox JavaScript

Hello I want to disable two buttons when the checkbox is checked but for it result I must click two times in the checkbox hope someone can help me.

Thanks.

var checker = document.getElementById('checkme');
var button = document.getElementById('button');
var button2 = document.getElementById('button2');

document.getElementById("button").disabled = true;
document.getElementById("button2").disabled = true;


checker.onchange = function() {

button.disabled !! this.checked;
button2.disabled !! this.checked;

};

Your code is wrong. You have to assign the checkbox status to button:

 var checker = document.getElementById('checkme'); var button = document.getElementById('button'); var button2 = document.getElementById('button2'); document.getElementById("button").disabled = true; document.getElementById("button2").disabled = true; checker.onchange = function() { button.disabled = !this.checked; button2.disabled = !this.checked; }; 
 <input type='checkbox' id='checkme' /> <button id='button'>Button 1</button> <button id='button2'>Button 2</button> 

simply use this code

<input type="checkbox" id="checkme" onChange="state_change(this.checked)">
<input type="button" id="button" value="button1">
<input type="button" id="button2" value="button2">
<script type="text/javascript">
function state_change(check){
    document.getElementById('button').disabled = check;
    document.getElementById('button2').disabled = check;
}
</script>

I suggest defining 'button' and 'button2' inside the function, otherwise it could be overwritten if you define 'button' somewhere else. Instead of manually initializing the disabled state you can simply call the onchange function directly, which will make possible modifications to the code easier, you generally want to avoid having the same code in multiple places.

 var checker = document.getElementById('checkme'); checker.onchange = function() { var button = document.getElementById('button'); var button2 = document.getElementById('button2'); button.disabled = !this.checked; button2.disabled = !this.checked; }; checker.onchange(); 
 <input type="checkbox" id="checkme"> <button id = "button">button</button> <button id = "button2">button2</button> 

Ha ha ha who say this sendbtn2.disabled = !!this.checked; Hope this help you. sendbtn2.disabled = !!this.checked; Hope this help you. .

Why a = !! b a = !! b because !!= not not and = true, then write a=b .

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