Attach event listener through javascript to radio button

前端 未结 5 807
春和景丽
春和景丽 2020-12-03 08:13

I have several radio buttons with the same name. Like this:

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-03 08:45

    You could add just a single listener that listens to all radio buttons, rather than individual listeners.

    using jquery, you could do it like this

    $(document).ready(function(){
        $('input[type=radio]').click(function(){
            alert(this.value);
        });
    });
    

    Demo

    For only the radios within a form with id formA

     $(document).ready(function(){
            $('#formA input[type=radio]').click(function(){
                alert(this.value);
            });
        });
    

    For only radios with an id myradio

    $(document).ready(function(){
        $('input[type=radio]').click(function(){
            if (this.id == "myradio")
                alert(this.value);
        });
    });
    

    Demo

提交回复
热议问题