简体   繁体   中英

Marking Radio Button checked by default

I have a form in which i am trying to auto populate the value of radio button.

content=content+' <label class="radio-inline">';                
content=content+' <input type="radio" name="ip_radio_resp_'+questDetail.qId+'" id="radioYes"  value="Y" onclick="removeFocusOnComment('+questDetail.qId+');showReasonTextBox('+questDetail.qId+')"> Yes';
content=content+' </label>

I am checking for value for some other field, if I get the desired response I marked radio btn else not

switch(questDetail.metricsValue){
case 'Y':

    $('#ip_radio_resp_'+questDetail.qId).each(function() {
        $('input:radio[name="ip_radio_resp_'+questDetail.qId+'"]#radioYes').prop('checked',true);
    });
    break;
case 'N' :
    //something......   
break;
default:
    //something
}

I am using jquery 1.11.2

But it constantly given me error undefined..I know this can be a duplicate and I tried all other answers given, but not able to get this working...can someone please help!!

Thanks in advance.

You can't have id="radioYes" in every radio group, because IDs must be unique. Use class="radioYes" instead. Then you can do:

case 'Y':
    $('input:radio[name="ip_radio_resp_'+questDetail.qId+'"].radioYes').prop('checked',true);
    break;

You don't need to use $('#ip_radio_resp_'+questDetail.qId).each because you're not doing anything with the element with that ID (I suspect you don't even have that element, and you were confusing name with id ).

i think you don't need all that, you just need to check while you making you radio buttons if the

questDetail.metricsValue == 'Y'

then you need to make it checked.

you can cancel all of you switch case you create and make it this way it will be easier for you.

    content=content+' <label class="radio-inline">';                
    content=content+' <input type="radio" name="ip_radio_resp_'+questDetail.qId+'" class="radiosToBeChecked" id="radioYes'+questDetail.qId+'" checked="'+(questDetail.metricsValue == 'Y') ? 'checked': ''+'" onclick="removeFocusOnComment('+questDetail.qId+');showReasonTextBox('+questDetail.qId+')"> Yes';
    content=content+' </label>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM