Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

jQuery: enable element on radio check

jQuery function isnt enabling my disabled submit button?

$(document).ready(function() {
      if ($("#lawfulBasis").prop("checked")) {
         $("#submitBtn").prop('disabled', false);   
       alert('Button Clicked');           
      };    
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>

<head>

</head>
<body>
<input id="lawfulBasis" type="radio" value="3" /> I give consent for you to store my data for the purposes of marketing, to contact me about products and services via email and telephone*
<p>
<input id="submitBtn" type="submit" value="Submit" disabled/>
</p>

</body>

</html>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The issue is because you only read the state of the radio control in the document.ready handler, ie. when the page loads not when the user changes its state.

To fix this attach a change event handler to the radio and set the disabled state of the button based on that.

Finally, note that you should be using a checkbox for this, not a radio. The reason is that the radio cannot be deselected once selected for the first time.

jQuery($ => {
  $("#lawfulBasis").on('change', e => {
    $("#submitBtn").prop('disabled', !e.target.checked);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<label>
  <input id="lawfulBasis" type="checkbox" value="3" /> 
  I give consent for you to store my data for the purposes of marketing, to contact me about products and services via email and telephone*
</label>
<p>
  <input id="submitBtn" type="submit" value="Submit" disabled/>
</p>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading