user6459745
user6459745

Reputation:

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

Upvotes: 1

Views: 448

Answers (2)

Nihar Sarkar
Nihar Sarkar

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

gaetanoM
gaetanoM

Reputation: 42044

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>

Upvotes: 0

Related Questions