简体   繁体   中英

basic javascript question about disabling buttons

I have a simple piece of javascript embedded into my html form, not a separate file, that is supposed to disable the submit form button until a certain checkbox has been checked but it doesn't seem to be working.

<script>
    var disclaimer = document.getElementById("disclaimer");
    var submitButton = document.getElementById("submit");

    submitButton.disabled = true;
    if (disclaimer.checked) {
        submitButton.disabled = false;
    }

 </script>

which I wrote and seems simple and effective but I'm not getting the results I'm looking for. After researching I see results such as

$('#check').click(function(){
if($(this).attr('checked') == false){
    $('#btncheck').attr("disabled","disabled");   
}
else
    $('#btncheck').removeAttr('disabled');
});

Now obviously the variable names and such are named differently but this doesn't even look remotely similar to the javascript code I've provided above and I'm having a hard time getting useful tips from the apparently working code below that does the same thing. Could someone break down the code segment below such that I might be able to fix my code above?

This is the snippet of code with the two HTML id's in question,

<label style='font-size: smaller;'>
  <input type='checkbox' name='disclaimer' id='disclaimer' required='required' />
  I understand that by submitting this form, 
  I am transferring any copyright and intellectual property rights to the form's owner, 
  that I have the right to do so,
  and that my submission is not infringing on other people's rights.
</label><br/>

<script>
    var disclaimer = document.getElementById("disclaimer");
    var submitButton = document.getElementById("submit");

    submitButton.disabled = true;
    if (disclaimer.checked) {
        submitButton.disabled = false;
    }

 </script>


  <div class='vspace'/>
  <input type='submit' id='submit' name='came-from-form'/>

Edit: Tons of great answers below that were very informative for letting me know what I'm working with. The issue I'm now facing is implementing these things. In the snippets below this seems very easy to implement but as I try to implement each answer below I'm not seeing any results which clearly means I'm doing something wrong somewhere else in my form. I've attached a larger snippet of the code in question if it helps. Otherwise it might be best to ask a new question.

I believe you trying to find the solution in vanilla JavaScript.

You have to attach the event to the check element like the following way:

 var disclaimer = document.getElementById("disclaimer"); document.getElementById("submit").disabled = true; disclaimer.addEventListener('click', function(){ var submitButton = document.getElementById("submit"); submitButton.disabled = true; if (this.checked) { submitButton.disabled = false; } }); 
 <form> <input type="checkbox" id="disclaimer"/> <button id="submit">Submit</button> </form> 

Update:

In your code, the script is executing before the DOM is fully loaded. Hence you get a error:

Uncaught TypeError: Cannot set property 'disabled' of null

You can either place the script at the end or wrap your code with

DOMContentLoaded

The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A very different event load should be used only to detect a fully-loaded page. It is an incredibly common mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.

 <label style='font-size: smaller;'> <input type='checkbox' name='disclaimer' id='disclaimer' required='required' /> I understand that by submitting this form, I am transferring any copyright and intellectual property rights to the form's owner, that I have the right to do so, and that my submission is not infringing on other people's rights. </label><br/> <script> document.addEventListener("DOMContentLoaded", function(event) { var disclaimer = document.getElementById("disclaimer"); document.getElementById("submit").disabled = true; disclaimer.addEventListener('click', function(){ var submitButton = document.getElementById("submit"); submitButton.disabled = true; if (this.checked) { submitButton.disabled = false; } }); }); </script> <div class='vspace'/> <input type='submit' id='submit' name='came-from-form'/> 

Quick Explantion

Here's a quick explanation of the code, which is heavily reliant on the JavaScript library, jQuery :

// click() is called every time the element `id="check"` is clicked
$('#check').click(function(){

  // if element with `id="check"` has an attribute called *checked* set to false or it is null, then perform the if-block, otherwise perform the else-block
  if($(this).attr('checked') == false){
    // set disabled attribute of element with `id="btncheck"` to value of `disabled`
    $('#btncheck').attr("disabled","disabled");   
  }
  else
    // remove disabled attribute of element with `id="btncheck"`
    $('#btncheck').removeAttr('disabled');
});
  • anything in $() is selecting the element in the DOM, primarily using CSS-like selectors
  • .attr() is a method that gets/sets the element HTML attribute
  • .removeAttr() is a method that removes the HTML attribute

Vanilla JS

What you want to accomplish can be done with vanilla JS.

 const disclaimer = document.querySelector("#disclaimer"); const submit = document.querySelector("#submit"); submit.disabled = true; // default setting const clickHandler = (event) => submit.disabled = !event.target.checked; disclaimer.addEventListener('click', clickHandler ); // attach event 
 <form> <input type="checkbox" id="disclaimer"/> <button id="submit">Submit</button> </form> 

The only significant difference between the 2 code samples you posted is that the second one wraps the button disabling in the click event.

First one says : Straight when page is loaded, if the checkbox is checked, enable the button. (hint: happens only once)

Second one says : For each click on the checkbox, if the checkbox is checked, enable the button.

Something like this should work (haven't tested) :

<script>
    var disclaimer = document.getElementById("disclaimer");
    var submitButton = document.getElementById("submit");

    function disableSubmitIfDisclaimerNotAccepted(){
        submitButton.disabled = true;
        if (disclaimer.checked) {
            submitButton.disabled = false;
        }

    }

    disclaimer.onclick = disableSubmitIfDisclaimerNotAccepted; // everytime the checkbox is clicked
    disableSubmitIfDisclaimerNotAccepted(); // on page load
</script>

Hope this will work for you

  $('#disclaimer').click(function(){ if($(this).attr('checked') == false){ $('#submit').attr("disabled","disabled"); } else $('#submit').removeAttr('disabled'); }); 

Here if condition indicates the action which should be done if the disclaimer is not chcked. Button will be enable if the disclaimer is checked.

If you want jQuery, use prop (is not wrong to use attr too but I prefer prop instead). For checkbox, use change event instead of click . I'd do like:

$('#check').on("change", function(){
   var isChecked = $(this).is(':checked');
   $('#btncheck').prop("disabled", !isChecked); 
});

You must listen to input events in order to make changes when something change, like checking an checkbox.

var disclaimer = document.getElementById("disclaimer");
var submitButton = document.getElementById("submit");

submitButton.disabled = true;

disclaimer.addEventListener('change', function() {
  if (this.checked) {
    submitButton.disabled = false;
  } else {
    submitButton.disabled = true;
  }
})

More about events: https://developer.mozilla.org/en-US/docs/Web/Events

Submit button disabled by default in HTML :

<input type="checkbox" id="disclaimer">
<label for="disclaimer">Disclaimer</label>

<input type="submit" id="submit" disabled>

Simplest solution using ES6 syntax without JQuery :

let disclaimerCheckbox = document.getElementById('disclaimer'),
    submitButton       = document.getElementById('submit');

disclaimerCheckbox.onchange = () => submitButton.disabled = !disclaimerCheckbox.checked;

JSFiddle

NOTE : no need to use the DOMContentLoaded event if the script has the defer attribute .

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