user12542647
user12542647

Reputation:

Enabling a button when a checkbox is checked

I am trying to make a simple script that allows once a user checks the "termsChkbx" input field, then the button "submit" should get enabled but it does not. I Even try and inside the if statement place an alert function which works once it gets clicked, but not when I try and place the btn.disabled = false; in it. I am new to JavaScript and would appreciate if you can help me out

HTML

<form>
<section id="makeBooking">
<p style="color: #FF0000; font-weight: bold;" id='termsText'>I have read and agree to the terms and conditions
            <input type="checkbox" name="termsChkbx"></p>

            <p><input type="submit" name="submit" value="Book now!" disabled></p>
        </section>
</form

JavaScript

 window.addEventListener('load', function() {
        'use strict';

          const termsChkbx =  document.querySelector('[name="termsChkbx"]')
        termsChkbx.onclick = function(){

        const btn = document.querySelector("[name='submit']");

            if (termsChkbx.checked) {
                btn.disabled =false;
            }//if
            else {
                btn.disabled = true;
            }//else
        }//onclick
    });

Upvotes: 1

Views: 1530

Answers (4)

BCDeWitt
BCDeWitt

Reputation: 4773

I'd suggest a few additional changes to keep things cleanly separated into design (CSS), content/semantics (HTML) and functionality (JS), but you are mostly there in terms of it just working. That said, you should probably use the DOMContentLoaded event for this, instead:

// Functionality
document.addEventListener('DOMContentLoaded', () => {
  'use strict'
  
  const termsCheckboxEl = document.querySelector('.js-terms-chk')
  const bookButtonEl = document.querySelector('.js-book-btn')

  termsCheckboxEl.addEventListener('change', e => {
    bookButtonEl.disabled = !termsCheckboxEl.checked
  })
})
/* Design */
strong {
  color: #FF0000;
  font-weight: bold;
}

form {
  display: grid;
  gap: 1em;
  justify-items: start;
}
<!-- Content/Semantics -->
<form>
  <strong>
    I have read and agree to the terms and conditions
    <input class="js-terms-chk" type="checkbox" name="termsAccepted">
  </strong>
  <button class="js-book-btn" disabled>Book now!</button>
</form>

Some things to note in that snippet...

I used js-* classes instead of name attributes. Using js-* makes it apparent when looking at the HTML that changing the elements may break the JavaScript, but also allows the name attributes to freely change when they need to.

I also used <button> instead of <input type="submit">. This is considered the better alternative (mostly because a button can have HTML content and it's less to read/write)

To understand the other CSS and HTML changes, you'll need a change of perspective. Think about why you chose <p> tags here. I'd assume the answer is "because they have space around them" but that's just how it appears, not the content itself. These aren't actually paragraphs. A common best practice is to keep your design in CSS (as much as it allows) and choose HTML so it makes sense as-is, without being rendered. Inline styles (style="...") are obviously against this best practice, but what isn't always obvious is the choices of elements and class names in HTML. A bit more on this topic can be found in the HTML5 W3C Recommendation

Upvotes: 0

Summy
Summy

Reputation: 533

You would have to disable the submit button initially itself and later after the checkbox is clicked, you can check if checkbox is checked or not.

window.addEventListener('load', function() {
      'use strict';
      const termsChkbx =  document.querySelector('[name="termsChkbx"]');
      const btn = document.querySelector("[name='submit']");
      // you would have to disable the button initially itself
      btn.disabled = true;

      termsChkbx.onclick = function(){
        if (termsChkbx.checked) {
          btn.disabled = false;       
        }
        else {
          // you would need this else statement also because if the user clicks the checkbox again, it would get unchecked and you would probably want the submit button to get back to disabled state
          btn.disabled = true;
        }
      }
});

or else you can do the way @BrOsCoRe has answered, I would prefer the way he has done.

Upvotes: 0

BrOsCoRe
BrOsCoRe

Reputation: 73

Try this

JSFiddle

var checkbox = document.querySelector("input[name=termsChkbx]");
var btn = document.querySelector("input[name=submit]");

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

source: stackOverflow

Upvotes: 3

Bara Ahmad
Bara Ahmad

Reputation: 21

Try this

<form>
<section id="makeBooking">
<p style="color: #FF0000; font-weight: bold;" id='termsText'>I have read and agree to the terms and conditions
            <input type="checkbox" name="termsChkbx" onclick="Enable()" id="checkBoxId"></p>

            <p><input type="submit" id="btnId" name="submit" value="Book now!" disabled></p>
        </section>
</form>
<script>
function Enable(){
  $('#btnId').prop("disabled", !$("#checkId").prop("checked")); 
}
</script>

Upvotes: 0

Related Questions