Vimal
Vimal

Reputation: 1146

Do a event by checking which radio button is checked using jquery

I need to show different div based on which radio button is checked.I have done it by using change event method.but i need to do do it when the page is loaded by looking which is checked.

$('#id_radio1').click(function () {
    $('#div2').hide('fast');
    $('#div1').show('fast');
});

the radio buttons are

<div class="col-md-4">       
     <label>
     <input type="radio" name="sublink" id="id_radio2" value="0" <?php if($announcements_details['detail_type']=="0") echo' checked="checked"'?> >&nbsp;Add attachment to title</input>
    </label>
</div>
<div class="col-md-4">      
    <label>     
        <input type="radio" name="sublink" id="id_radio1"  value="1" <?php if($announcements_details['detail_type']=="1") echo' checked="checked"'?> >&nbsp;Add new sublinks</input>
    </label>
</div>
<div class="col-md-4">      
    <label>             
        <input type="radio" name="sublink" id="id_radio3" value="2" <?php if($announcements_details['detail_type']=="2") echo' checked="checked"'?>>&nbsp;None
    </label>
</div>

Help me solving this

Upvotes: 3

Views: 127

Answers (2)

Hezron
Hezron

Reputation: 352

JS Jquery

Get checked radio when page loaded.

$("input[name=sublink]").each(function(index, elem){
 if($(this).prop("checked")){

    console.log("radio (with checked) has value: "+elem.value);

    if(elem.value == "0"){
        // LOGIC FOR SHOW/HIDE DIV HERE
    } else if(elem.value == "1"){
        // LOGIC FOR SHOW/HIDE DIV HERE
    } else if(elem.value == "2"){
        // LOGIC FOR SHOW/HIDE DIV HERE
    }
 }
});

.....

If you need this. Get checked radio when click a input-radio.

$("input[name=sublink]").on("change", function(){
 switch(this.value){
 case "0":
 console.log("radio with value 0");
 // LOGIC FOR SHOW/HIDE DIV HERE
 break;
 case "1":
 console.log("radio with value 1");
 // LOGIC FOR SHOW/HIDE DIV HERE
 break;
 case "2":
 console.log("radio with value 2");
 // LOGIC FOR SHOW/HIDE DIV HERE
 break;
 default:
 console.log("default");
 }
});

Upvotes: 1

Jai
Jai

Reputation: 74738

You can use this code to show the respective div:

function showdiv() {
  var div = "#div" + $(':radio:checked').val(); // <---get the div id like #div1
  $(div).show('fast').siblings('div[id^="div"]').hide(); // <---show the respective one and
}                                                        // hide others
$(function(){
   showdiv(); //<---on doc ready call this function here.
   $(':radio').click(showdiv);
});

Upvotes: 1

Related Questions