Search code examples
javascripthtmljqueryradio-buttonrequired

How can I enable next button only if either one of the radio button is checked?


i have a website which displays some questions to users, each questions has 4 options in radio buttons, my code looks like below:

$('div.question').hide().first().show();

$('a.display').on('click', function(e) {
      e.preventDefault();
      var that = $('div.question:visible'),
        t = $(this).text();

      if (t == 'next' && that.next('div.question').length > 0) {
        $('div.question').hide();
        that.next('div.question').show()
      }
  });
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<div class="question bg-white p-3 border-bottom">
  <div class="d-flex flex-row  question-title">
    <h3 class="text-danger">1. </h3>
    <h5 class="mt-1 ml-2">I try to be with people.</h5>
  </div>

  <div class="ans ml-2">
    <div class="form-check">
      <input class="form-check-input" name="q1" value="1" type="radio">
      <input class="form-check-input" name="q1" type="radio" value="2">
      <input class="form-check-input" name="q1" type="radio" value="3">
      <input class="form-check-input" name="q1" type="radio" value="4">
    </div>
  </div>
</div>

<a id="display" class="btn btn-info btn-sm display si">next</a>

this is what i did, but the problem is user can go to next question without checking radio button, i want to restrict that, user should check any of the radio button to proceed to next question, can anyone please tell me how to accomplish this, thanks in advance


Solution

  • Another way is adding events on the html and hiding the button at the beginning.

    <input class="form-check-input" name="q1" type="radio" value="1" onclick="handleClick(event);" />
    <input class="form-check-input" name="q1" type="radio" value="2" onclick="handleClick(event);" />
    <input class="form-check-input" name="q1" type="radio" value="3" onclick="handleClick(event);" />
    <input class="form-check-input" name="q1" type="radio" value="4" onclick="handleClick(event);" />
    

    js.

    $("#display").hide();
    function handleClick(e) {
      //console.log(e.target.value);
      $("#display").show();
    }