Chitika

Friday, July 3, 2020

Un Check radio button on second time selected

Radio button in general can't be un checked when we select for the second time.
We can do it using code.

Ex: if we have below radio buttons

<input type="radio" id="rbnEgg" name="rdNV" value="Egg" runat="server"  />
  <label for="rbnEgg">Egg</label>
  <input type="radio" id="rbnChicken" name="rdNV" value="Chicken" runat="server" />
  <label for="rbnChicken">Chicken</label>

Use below script to check and uncheck the selection

<script language="javascript">
 $(document).on("click", "input[name='rdNV']", function(){
    thisRadio = $(this);
    if (thisRadio.hasClass("imChecked")) {
        thisRadio.removeClass("imChecked");
        thisRadio.prop('checked', false);
    } else {
        thisRadio.prop('checked', true);
        thisRadio.addClass("imChecked");
        if (thisRadio.context.id == 'rbnEgg') {
            $('input[id=rbnChicken]').removeClass("imChecked");
            $('input[id=rbnChicken]').prop('checked', false);
        }
        else if (thisRadio.context.id == 'rbnChicken') {
           $('input[id=rbnEgg]').removeClass("imChecked");
           $('input[id=rbnEgg]').prop('checked', false);
        }
    };
        })

Here i am un-checking only one radio button, if there are multiple radio buttons uncheck all the radio buttons before the statement : thisRadio.prop('checked', true);

No comments:

Post a Comment