Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap set radio button checked with jquery

I have radio buttons in my html code. I want to change their state based on my input values via jquery

Here is My Html

<div class="col-md-2 col-xs-offset-1">
 <div class="radio">
  <label>
    <input type="radio" name="rdo_pkdrop" value="0" id="rdo_pick">
     Pick-up Time
   </label>
 </div>
 <div class="radio">
  <label>
   <input type="radio" name="rdo_pkdrop" id="rdo_drop" value="1">
    Drop Time
   </label>
 </div>
</div>

An jQuery is

if(qs_trip_type == 0){
   $('#rdo_pick').prop('checked',true); 
}else{
   $('#rdo_pick').prop('checked',true); 
}

But This has no effect I also tried with $('#rdo_pick').prop('checked','checked'); and

$('#rdo_pick').attr('checked','true'); 
  $('#rdo_pick').addClass('checked');
like image 908
Vijay Tambade Avatar asked Jan 23 '15 07:01

Vijay Tambade


3 Answers

This is only way I could find. Although somewhat inelegant, it does work.

if(qs_trip_type == 0){
  $('#rdo_pick').click(); 
}else{
  $('#rdo_drop').click(); 
}
like image 151
lanternmarsh Avatar answered Nov 15 '22 07:11

lanternmarsh


The issue with bootstrap is that you set a checked radio button by adding the active class to the corresponding label of the input. It looks like this:

<label class="btn btn-default active">    <!-- Note the class 'active' here -->
    <input type="radio" name="myRadio" value="value1" checked="checked"/>Value 1
</label>
<!-- ... -->

To check a radio button using jQuery you could first select the input field with a jQuery Selector and then add the class to the parent:

var $myRadioInput = $(...);
$myRadioInput.parent('.btn').addClass('active');

Don't forget to remove the class active on the formerly selected label with jQuery removeClass('active') to first unselect them.

I also like it to set the checked property on the input itself to have the proper state on it:

$myRadioInput.prop('checked', true);

Note that the checked="checked" attribute is only the inital state for the input to be the checked input when loading the page. It does NOT change with the jQuery .prop() method, as it is an attribute and is different to the actual checked property. This is well described in jQuery Docs.

like image 34
Michbeckable Avatar answered Nov 15 '22 06:11

Michbeckable


I have tried,this code is ok for bootstrap radio.

if(qs_trip_type == 0){
   $('#rdo_pick').prop('checked',true).click();
}else{ //not ekse
   $('#rdo_pick').prop('checked',true).click();
}
like image 2
tdkman2010 Avatar answered Nov 15 '22 05:11

tdkman2010