Mr X
Mr X

Reputation: 1739

jQuery to select and update radio button value

I am using the below jQuery to take the data from radio button, every-time it is showing the first checked option, on changing the option it is not updating and keep alerting the same option.

jQuery:

$(document).ready(function () {

    if ($("input[name=options_1]").is(':checked')) {
       $ans = $("input[name=options_1]:checked").val();
       $(':radio').removeProp('checked');
       $(".submit_ans").click(function () {

          alert($ans);
          $('.viewans').removeClass('disabled');
          $('.next_ques').removeClass('disabled');
       });
       $('.next_ques').click(function () {
          $('.ques_1').hide();
          $('.ques_2').show(); // the html has other questions as well but not shown in the code below. 
          $('.viewans').addClass('disabled');
          $('.next_ques').addClass('disabled');

       });
    }

    $(".viewans").click(function () {
       $(".hide_options").toggle("slow");
    });

 });

HTML :

<div class="form-horizontal">
   <div class="radio col-lg-3">
      <label>
         <input type="radio" value="a" id="optionsRadios1" name="options_1">
      </label>
   </div>
   <div class="radio col-lg-3">
      <label>
         <input type="radio" value="b" id="optionsRadios2" name="options_1">b
      </label>
   </div>
   <div class="radio col-lg-3">
      <label>
         <input type="radio" value="c" id="optionsRadios3" name="options_1">c</label>
   </div>
   <div class="radio col-lg-3">
      <label>
         <input type="radio" value="d" id="optionsRadios4" name="options_1">d
      </label>
   </div>
</div>

Upvotes: 0

Views: 445

Answers (1)

Tuhin
Tuhin

Reputation: 3373

enclose the if condition within a change event of options_1 :

$("input[name=options_1]").change(function(){
..
}

like:

 $("input[name=options_1]").change(function(){
     if($("input[name=options_1]").is(':checked'))
            {
                $ans = $("input[name=options_1]:checked").val();
                $(':radio').removeProp('checked');
                       alert($ans);

            }
  });

FIDDLE DEMO

Upvotes: 1

Related Questions