Reputation:
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
Upvotes: 1
Views: 448
Reputation: 1299
Try this: Edited
JAVASCRIPT :
$("a").click(function(){
$('input[name="field"][value="b"]').attr('checked', true);
});
HTML :
<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>
Upvotes: 2
Reputation: 42044
It is not always possible to use input type reset. So, you need for the first:
$(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>
Upvotes: 0