Add attribute 'checked' on click jquery

前端 未结 5 2072
滥情空心
滥情空心 2020-12-30 00:49

I\'ve been trying to figure out how to add the attribute \"checked\" to a checkbox on click. The reason I want to do this is so if I check off a checkbox; I can have my loca

相关标签:
5条回答
  • 2020-12-30 01:02

    use this code

    var sid = $(this);
    sid.attr('checked','checked');
    
    0 讨论(0)
  • 2020-12-30 01:07

    $( this ).attr( 'checked', 'checked' )

    just attr( 'checked' ) will return the value of $( this )'s checked attribute. To set it, you need that second argument. Based on <input type="checkbox" checked="checked" />

    Edit:

    Based on comments, a more appropriate manipulation would be:

    $( this ).attr( 'checked', true )
    

    And a straight javascript method, more appropriate and efficient:

    this.checked = true;
    

    Thanks @Andy E for that.

    0 讨论(0)
  • 2020-12-30 01:10

    A simple answer is to add checked attributes within a checkbox:

    $('input[id='+$(this).attr("id")+']').attr("checked", "checked");

    0 讨论(0)
  • 2020-12-30 01:21

    If .attr() isn't working for you (especially when checking and unchecking boxes in succession), use .prop() instead of .attr().

    0 讨论(0)
  • 2020-12-30 01:22

    It seems this is one of the rare occasions on which use of an attribute is actually appropriate. jQuery's attr() method will not help you because in most cases (including this) it actually sets a property, not an attribute, making the choice of its name look somewhat foolish. [UPDATE: Since jQuery 1.6.1, the situation has changed slightly]

    IE has some problems with the DOM setAttribute method but in this case it should be fine:

    this.setAttribute("checked", "checked");
    

    In IE, this will always actually make the checkbox checked. In other browsers, if the user has already checked and unchecked the checkbox, setting the attribute will have no visible effect. Therefore, if you want to guarantee the checkbox is checked as well as having the checked attribute, you need to set the checked property as well:

    this.setAttribute("checked", "checked");
    this.checked = true;
    

    To uncheck the checkbox and remove the attribute, do the following:

    this.setAttribute("checked", ""); // For IE
    this.removeAttribute("checked"); // For other browsers
    this.checked = false;
    
    0 讨论(0)
提交回复
热议问题