0

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.

1
  • Im not sure if you are aware but the second code is jQuery (a javascript library). It really helps but you could still get the same result with plain javascript. What you are missing is event listeners. Commented Nov 7, 2018 at 6:51

7 Answers 7

1

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'/>

Sign up to request clarification or add additional context in comments.

5 Comments

yes this is certainly the way I'm trying to implement this simply just vanilla javascript. I've tried implementing your answer but just doesn't seem to be working. Obviously this is something on my end of implementation since this very clearly works. Would I need to put this snippet in <script> tags AFTER I create the <input type='submit' id='submit'/>?
@Mikel, yes you can try that....but I will suggest you to update the question with relevant HTML if possible....as this will help understand the real issue and find the solution easily.......thanks.
will do! one moment
yes this works great @Mamun could you explain what you changed about the form for it to work? particularly in the script tags, what is the "DOMContentLoaded"? Thanks again
@Mikel, DOMContentLoaded ensures that all the code written inside will be executed after the all the HTML loaded.....I have added some details and a link. Please visit the link for more information.......thanks.
1

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>

1 Comment

Thank you this was very informative on both sides of my question! I had a really hard time trying to comprehend the syntax and whether or not it was actually vanilla javascript I was looking at.
0

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.

Comments

0

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); 
});

Comments

0

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>

2 Comments

The desired behavior I'm looking for is for the submit button to be disabled upon loading the page and once the checkbox has been checked to enable the button. Is that not what I'm achieving in the first code segment?
No, the first code only happens on initial page load.
0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.