The King is The King is - 3 months ago 9
jQuery Question

Checking a radio input field by its value

I have searched for the answer but all I got couldn't solve my problem.

I want to

checked
a radio
input
like this

<input type="radio" name="field" value="a" />
<input type="radio" name="field" value="b" checked />
<input type="radio" name="field" value="c" />
<a href="javascript:;">cancel</a>

// jQuery
$("a").click(function(){
var checked = "b";
$('input').each(function(){
var value = $(this).val();
if(value == checked){
$(this).attr('checked', true);
} else {
$(this).attr('checked', false);
}
});
});


Now this is what I want to achieve, the default value is "b" so if a user clicks "a" or "c" and wants to return the value back to "b" without clicking "b" and clicks the link I want the value "b" to be checked and thereby unchecking the other values. But when I run the code, it just uncheck all the values.
How can I achieve this using jQuery

Answer

It is not always possible to use input type reset. So, you need for the first:

  • save the currently checked radio index
  • set checked this radio when you click on the link:

$(function () {
  $("a").data('radio-checked-index', $(':radio:checked').index(':radio'));
  $("a").click(function(){
    var checkedIndex =  +$("a").data('radio-checked-index');
    $(':radio:eq(' + checkedIndex + ')').prop('checked', true);
  });
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<form>
    <input type="text">
    <input type="radio" name="field" value="a" />
    <input type="radio" name="field" value="b" checked />
    <input type="radio" name="field" value="c" />
    <input type="reset">
    <a href="javascript:;">cancel</a>
</form>

Comments