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>
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.
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.
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.
$('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
$("input[value='Good']").attr("id");
If you want to select the input by its value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With