1

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

  • Is that wrapped inside a `form`? If ya, just use input type reset. https://jsfiddle.net/2okpwafw/ Otherwise, you could use: https://jsfiddle.net/2okpwafw/1/ – A. Wolff Aug 14 '16 at 16:46
  • 1
    change `.attr` to `.prop` see : http://stackoverflow.com/questions/426258/setting-checked-for-a-checkbox-with-jquery – winghei Aug 14 '16 at 16:50
  • 1
    @Wolff, that will reset all the form values if he has more inputs in the form and I guess he wants to reset only the radio box – KANAYO AUGUSTIN UG Aug 14 '16 at 17:01

2 Answers2

2

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>
Nihar Sarkar
  • 1,187
  • 1
  • 13
  • 26
0

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>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61