[javascript] How to disable/enable a button with a checkbox if checked

Please i need a script that can work with the HTML code bellow to disable/enable the button when a checkbox is checked or unchecked,

<input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />

please pals i don't mean the button to be disabled when checked, but rather the other way round.

This question is related to javascript html

The answer is


HTML

<input type="checkbox" id="checkme"/><input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />

JS

var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
checker.onchange = function() {
  sendbtn.disabled = !!this.checked;
};

DEMO


I recommend using jQuery as it will do all the heavy lifting for you. The code is fairly trivial.

$('input:checkbox').click(function () {
  if ($(this).is(':checked')) {
    $('#sendNewSms').click(function () {
      return false;
    });
  } else {
    $('#sendNewSms').unbind('click');
  }
});

The trick is to override the 'click' event and effectively disable it. You can also follow it up with some CSS magic to make it look "disabled". Here is the code in JavaScript in case you need it. It's not perfect but it gets the point across.

var clickEvent = function () {
  return false;
};
document.getElementById('#checkbox').onclick(function () {
  if (document.getElementById('#checkbox').checked) {
    document
      .getElementById('#sendNewSms')
      .onclick(clickEvent);
  } else {
    document
      .getElementById('#sendNewSms')
      .removeEventListener('click', clickEvent, false);
  }
});

Here is a clean way to disable and enable submit button:

<input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />
<input type="checkbox" id="disableBtn" />

var submit = document.getElementById('sendNewSms'),
    checkbox = document.getElementById('disableBtn'),
    disableSubmit = function(e) {
        submit.disabled = this.checked
    };

checkbox.addEventListener('change', disableSubmit);

Here is a fiddle of it in action: http://jsfiddle.net/sYNj7/


You will have to use javascript, or the JQuery framework to do that. her is an example using Jquery

   $('#toggle').click(function () {
        //check if checkbox is checked
        if ($(this).is(':checked')) {

            $('#sendNewSms').removeAttr('disabled'); //enable input

        } else {
            $('#sendNewSms').attr('disabled', true); //disable input
        }
    });

DEMO: http://jsfiddle.net/T6hvz/


You can use onchangeevent of the checkbox to enable/disable button based on checked value

<input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />

<input type="checkbox"  onchange="document.getElementById('sendNewSms').disabled = !this.checked;" />