Home > Back-end >  How can I enable next button only if either one of the radio button is checked?
How can I enable next button only if either one of the radio button is checked?

Time:05-28

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 >
  <div >
    <h3 >1. </h3>
    <h5 >I try to be with people.</h5>
  </div>

  <div >
    <div >
      <input  name="q1" value="1" type="radio">
      <input  name="q1" type="radio" value="2">
      <input  name="q1" type="radio" value="3">
      <input  name="q1" type="radio" value="4">
    </div>
  </div>
</div>

<a id="display" >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

CodePudding user response:

I've hide the "next" with style="display:none; and added this javascript-code to the end:

<script type="text/javascript">
  $('.form-check-input').click(function(){
    $('#display').show();
  });
</script>

so the "next" will be displayed as soon as the user clicks on one of the radio-buttons.

The complete version reads

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<div >
  <div >
    <h3 >1. </h3>
    <h5 >I try to be with people.</h5>
  </div>

  <div >
    <div >
      <input  name="q1" value="1" type="radio">
      <input  name="q1" type="radio" value="2">
      <input  name="q1" type="radio" value="3">
      <input  name="q1" type="radio" value="4">
    </div>
  </div>
</div>
<a id="display"  style="display:none;">next</a>
<script type="text/javascript">
  $('.form-check-input').click(function(){
    $('#display').show();
  });
</script>

CodePudding user response:

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

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

js.

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