开发者

Jquery set attribute for a label

开发者 https://www.devze.com 2022-12-26 05:31 出处:网络
Is it possible to set \"for\"(AssociatedControlID) attribute using jQuery? I am trying something like this to set it to the very next control that appears after label:

Is it possible to set "for"(AssociatedControlID) attribute using jQuery? I am trying something like this to set it to the very next control that appears after label:

$('label.asssociateClass').each(function()
{

      var toAssociate = $(this).next(':input');

      $(this).attr("for", toAssociate.attr("id"));

});

The problem is that if I don't set it开发者_JAVA百科 on a server through AssociatedControlID it never gets here since it's rendered as span instead of label in that case. Is there a way to overcome this or I have to do it on a server?


You can replace your spans with labels using .replaceWith() like this:

$('span.asssociateClass').each(function() {
  var l = $("<label class='associateClass' />")
           .html($(this).html())
           .attr('for', $(this).next(":input").attr("id"));
  $(this).replaceWith(l);
});​

Here's a quick example of it working: http://jsfiddle.net/V73WL/


you can't change behavior of asp:label, however you can change tag using jquery

$(function () {
    var spans = $('span.label').each(function() {
        input = $(this).next('input');      
        $('<label />').html($(this).html()).attr('for', input.attr('id')).insertBefore(input);
        $(this).remove();
    });
});
0

精彩评论

暂无评论...
验证码 换一张
取 消