Pedro D.
Pedro D.

Reputation: 99

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;

};

Upvotes: 1

Views: 87

Answers (4)

Michael
Michael

Reputation: 1089

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

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

Upvotes: 0

Drone
Drone

Reputation: 1134

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>

Upvotes: 1

Mandera
Mandera

Reputation: 3017

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>

Upvotes: 0

Alex Char
Alex Char

Reputation: 33228

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>

Upvotes: 2

Related Questions