简体   繁体   中英

On click radio button uncheck and check my new one

Hi i am using JavaScript to change the ticked radio button when the user clicks a new radio button.. now my problem is when i click the new one it hits the function fine but it has already checked the radio button meaning when i try to compare if it has been checked or not it will always come back as true, this means it wont remove the last ticked one and both will always be ticked.

JavaScript:

function Radio(a){

            var value = $(a).attr('value');
            var checked = a.checked;
            if (checked)
            {
                return;
            }
            else if (!checked)
            {
                $('.RadioClick').prop('checked', false);
                $(a).attr('checked', true);

            }

        }

html:

<input  onclick="Radio(this)" class="RadioClick" type="radio" value="1" checked>
<input onclick="Radio(this)" class="RadioClick" type="radio" value="2" >

Any help would be good? It needs to be a onclick for some factors so please only suggest ideas which are around the onclick way.

You get this behaviour for free with HTML - no need for any JS code here. You simply need to give both elements the same name property:

 1: <input name="foo" class="RadioClick" type="radio" value="1" checked="checked" /> 2: <input name="foo" class="RadioClick" type="radio" value="2" /> 

You should rather use same name as attribute to only select one radio button from group

<input name="test" class="RadioClick" type="radio" value="1" checked>
<input name="test" class="RadioClick" type="radio" value="2" >

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM