简体   繁体   中英

How to set radio button by default based on variable value

I have 2 radio buttons. How can I check it based on one variable value.

<input type="radio" name="team" id="team_7" value="7">
<input type="radio" name="team" id="team_8" value="8">

I have variable var number; which will set 7 or 8 based on some condition.

What I want is if number is 7, radio button team_7 will be checked by default, if it will be 8 radio button team_8 will be check by default.

You can create a dynamic jQuery selector using the number variable you have and select the radio button based on that.

Here is how you can select the default radio button using jQuery. Assuming number is the variable you have.

 var number = 'some value (7 or 8)';

 $('input[name=team][value=' + number + ']').prop('checked',true);

Just have a if-else statement to set the defaults on load or whenever the function is called.

    var num = 8;

    if(num === 8){
    $('#team_8').prop('checked',true);
    }
    else if(num === 7){
    $('#team_7').prop('checked',true);
    }
    else{
    //do stuff if not 7 or 8
    }

Something like this should help.

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