Radio button second click makes uncheck

Viewed 45

If my radio button previously checked and i try to uncheck with second click i have to click once more. So it means if my radio button previously checked i got to clicked 2 times for unchecked but it should works with only 1 click . How can i fix it. Here is 2 codes they both have the same issue. I show both scripts here .Thanks For Helping!

 $(function(){
    $('input[name="rad"]').click(function(){
        var $radio = $(this);

        // if this was previously checked
        if ($radio.data('waschecked') == true)
        {
            $radio.prop('checked', false);
            $radio.data('waschecked', false);
        }
        else
            $radio.data('waschecked', true);

        // remove was checked from other radios
        $radio.siblings('input[type="radio"]').data('waschecked', false);
    });
});

 $("input:radio").on("click", function (e) {
    var inp = $(this);
    if (inp.is(".clicked")) {
        inp.prop("checked", false).removeClass("clicked");
    } else {
        $("input:radio[name='" + inp.prop("name") + "'].clicked").removeClass("clicked");
        inp.addClass("clicked");
    }
});

<input type="radio" name="rad" id="Radio0" checked="checked"/>
<input type="radio" name="rad" id="Radio1" />
<input type="radio" name="rad" id="Radio2" />
<input type="radio" name="rad" id="Radio4" />
<input type="radio" name="rad" id="Radio3" />

and here is my html and jsfiddle

http://jsfiddle.net/fbyg1htz/

http://jsfiddle.net/7g684219/

1 Answers

The input element which is selected by default (checked="checked") should have the waschecked data attribute set to true because it's already checked.

<input type="radio" name="rad" id="Radio0" data-waschecked="true" checked="checked"/>

And the same for the second example. You should add class="clicked" to the element that is initially checked.

<input type="radio" name="rad" id="Radio0" class="clicked" checked="checked"/>

Updated fiddles:

http://jsfiddle.net/6fqLexbr/

http://jsfiddle.net/rmuh1sz3/

Example with razor for your first script:

<input type="radio" id="status_active" value="true" asp-for="ActiveOrPassive"
       data-waschecked="@Model.OrderFilter.ActiveOrPassive.ToString().ToLower()" />

and for your second script:

<input type="radio" id="status_active" value="true" asp-for="ActiveOrPassive"
       class="@(Model.OrderFilter.ActiveOrPassive ? "clicked" : null)" />
Related