Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery get id of radio button by testing value

I have a read only form that I want to populate the values returned from an ajax query. What I don't understand is the correct syntax to get the id of a specific radio button. I know what value exists in the db, but how to get the id of the radio button, to change the radio button attribute?

For example, in the Radio Button options with the "name"==Criteria1Score", how to I return the id of the input where value ==Good.

Here is an example of the form structure:

<legend>Criteria1</legend>
<label class="radio inline">
    Great
    <input id="Criteria1Score1" class="Score" name="Criteria1Score" type="radio" value="Great">
</label>
<label class="radio inline">
    Good
    <input id="Criteria1Score2" class="Score" name="Criteria1Score" type="radio" value="Good">
</label>
<label class="radio inline">
    Bad
    <input id="Criteria1Score3" class="Score" name="Criteria1Score" type="radio" value="Bad">
</label>
like image 822
manisha Avatar asked May 21 '13 23:05

manisha


People also ask

How can I select checked radio button in jQuery?

We can check the status of a radio button by using the :checked jQuery selector together with the jQuery function is . For example: $('#el').is(':checked') . It is exactly the same method we use to check when a checkbox is checked using jQuery.

How do you check if a radio button is checked Javascript?

Using Input Radio checked property: The Input Radio checked property is used to return the checked status of an Input Radio Button. Use document. getElementById('id'). checked method to check whether the element with selected id is check or not.

What is value in radio button HTML?

Note: The value attribute defines the unique value associated with each radio button. The value is not shown to the user, but is the value that is sent to the server on "submit" to identify which radio button that was selected.


2 Answers

$('input[type=radio][name=Criteria1Score]:checked').attr('id')

Working Demo:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<legend>Criteria1</legend>
<label class="radio inline">
    Great
    <input id="Criteria1Score1" class="Score" name="Criteria1Score" type="radio" value="Great"/>
</label>
<label class="radio inline">
    Good
    <input id="Criteria1Score2" class="Score" name="Criteria1Score" type="radio" value="Good"/>
</label>
<label class="radio inline">
    Bad
    <input id="Criteria1Score3" class="Score" name="Criteria1Score" type="radio" value="Bad"/>
</label>

<input type="button" onclick="alert($('input[type=radio][name=Criteria1Score]:checked').attr('id'))" value="click me to get id of checked input" />

JSFiddle

like image 98
km6zla Avatar answered Sep 19 '22 14:09

km6zla


$("input[value='Good']").attr("id");

If you want to select the input by its value

like image 43
Robin Manoli Avatar answered Sep 18 '22 14:09

Robin Manoli