.attr('checked','checked') does not work

后端 未结 7 2172
醉话见心
醉话见心 2020-12-13 06:15

I am trying to check radio. Neither the following works:

[edit]

$(\'selector\').attr(\'checked\',\'checked\');
$(\'selector\').attr(\'checked\',true)         


        
相关标签:
7条回答
  • 2020-12-13 06:50

    It works, but

    $('input[name="myname"][checked]').val()
    

    will return the value of the first element with attribute checked. And the a radio button still has this attribute (and it comes before the b button). Selecting b does not remove the checked attribute from a.

    You can use jQuery's :checked:

    $('input[name="myname"]:checked').val()
    

    DEMO


    Further notes:

    • Using $('b').attr('checked',true); is enough.
    • As others mentioned, don't use inline event handlers, use jQuery to add the event handler.
    0 讨论(0)
  • 2020-12-13 06:56
    $("input:radio").attr("checked",true); //for all radio inputs
    

    or

    $("your id or class here").attr("checked",true); //for unique radios
    

    equally the same works for ("checked","checked")

    0 讨论(0)
  • 2020-12-13 06:57
    $('.checkbox').prop('checked',true); 
    $('.checkbox').prop('checked',false);
    

    ... works perfectly with jquery1.9.1

    0 讨论(0)
  • 2020-12-13 07:00
     $('.checkbox').attr('checked',true);
    

    will not work with from jQuery 1.6.

    Instead use

    $('.checkbox').prop('checked',true);
    $('.checkbox').prop('checked',false);
    

    Full explanation / examples and demo can be found in the jQuery API Documentation https://api.jquery.com/attr/

    0 讨论(0)
  • 2020-12-13 07:03

    I don't think you can call

    $.attr('checked',true);
    

    because there is no element selector in the first place. $ must be followed by $('selector_name'). GOod luck!

    0 讨论(0)
  • 2020-12-13 07:06

    With jQuery, never use inline onclick javascript. Keep it unobtrusive. Do this instead, and remove the onclick completely.

    Also, note the use of the :checked pseudo selector in the last line. The reason for this is because once the page is loaded, the html and the actual state of the form element can be different. Open a web inspector and you can click on the other radio button and the HTML will still show the first one is checked. The :checked selector instead filters elements that are actually checked, regardless of what the html started as.

    $('button').click(function() {
        alert($('input[name="myname"][value="b"]').length);
        $('input[name="myname"][value="b"]').attr('checked','checked');
        $('#b').attr('checked',true);
        alert($('input[name="myname"]:checked').val());
    });
    

    http://jsfiddle.net/uL545/1/

    0 讨论(0)
提交回复
热议问题