Monday 22 August 2022

Check/Uncheck radio buttons like checkboxes in jQuery:

Html:

<input type="radio" name="gender" value="1" onclick="onChangeRadio(this)" data-prevval="0"/>

<input type="radio" name="gender" value="2" onclick="onChangeRadio(this)" data-prevval="0"/>


Jquery:

function onChangeRadio($this) {

        var productId = $($this).val();

        var checked = $($this).data("prevval");

        if (checked == 1) {

            $($this).prop("checked", false);

            $($this).data("prevval", 0);

        } else {

            $($this).data("prevval", 1);

        }

        var name = $($this).attr("name");

        $("input[name=" + name + "]").each(function () {

            var value = $(this).val();

            if (value != $($this).val()) {

                $(this).data("prevval", 0);

            }

        });

        var option;

        if ($($this).is(":checked")) {

            option = 0;

        } else {

            option = 1;

        }

        //do something

    }

No comments:

Post a Comment