简体   繁体   中英

radio button onchange/onclick event not work properly

I try to get value of radio button onclick or onchange event. But it only work for first item not for other item. When I click on first radio button it alert the radio button value. But when I click on other radion button it don't alert nothing.

My code is here

HTML

<input type="radio" value="1" name="layout" id="layout" class="ace">1
<input type="radio" value="2" name="layout" id="layout" class="ace">2
<input type="radio" value="3" name="layout" id="layout" class="ace">3
<input type="radio" value="4" name="layout" id="layout" class="ace">4

jQuery

$('#layout').on("click", function(e){
    alert($(this).val());
});

Try avoiding duplicate id's (Id should be unique on a page), instead use name attribute as shown below :-

$('input[name="layout"]').on("click", function(e){
  alert($(this).val());
});

ID attribute should be unique on the page. You need to use class instead:

HTML:

<input type="radio" value="1" name="layout" class="layout ace">1
<input type="radio" value="2" name="layout" class="layout ace">2
<input type="radio" value="3" name="layout" class="layout ace">3
<input type="radio" value="4" name="layout" class="layout ace">4

jQuery:

$('.layout').on("click", function(e){
    alert($(this).val());
});

From MDN :

The ID must be unique in a document, and is often used to retrieve the element using getElementById.

id attribute must be unique on the page. you always get the value of the first element with that id...

        <script>
        function first()
        {
            var a = document.getElementById("opt1").value;
            alert(a);
        }
        function second()
        {
            var b=document.getElementById("opt2").value;
            alert(b);
        }
        function third()
        {
            var c=document.getElementById("opt3").value;
            alert(c);
        }
        function fourth()
        {
            var d=document.getElementById("opt4").value;
            alert(d);
        }
        </script>

            <input type="radio" value="1"  name="layout" id="opt1" class="layout ace" onclick="first()">1
            <input type="radio" value="2"  name="layout" id="opt2" class="layout ace" onclick="second()">2
            <input type="radio" value="3"  name="layout" id="opt3" class="layout ace" onclick="third()">3
            <input type="radio" value="4"  name="layout" id="opt4" class="layout ace" onclick="fourth()">4

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