0

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.

1

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

4 Comments

first of all, you should # sign before putting team_8 id or team_7 id, second is your answer is too lengthy and in improper way.
Just typed something quickly but thanks for the catch, and also the OP never specified a way he would like an answer. So I just gave him a generic way to get the result OP is looking for.
Though It will work but Its not proper solution, there is no need to put if else condition if you can do it by one line in a proper way.
Sure there are multiple ways to get the answer, yes I'm aware. I'm just telling you I did a shorthand generic way of getting the results the OP wanted. I'm 100% there's a better solution than this, this is just one because OP never specified how he wanted his answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.