Nate
Nate

Reputation: 373

Wrap text with label

I am trying to get jQuery to set a label on the "untagged" element before a text input. However, it seems to be setting the label on the previous tag. I can't manually set a label in the code as it is auto-generated and the plugin developer has removed labels on form fields. Here is the code for one of the fields I have at the moment:

<div id="_dgx_donate_donor_first_name" class="text-input-section">
  <div id="_dgx_donate_donor_first_name-error-message" style="display:none" class="seamless-donations-error-message-field"></div>
  First Name:
  <input type="text" name="_dgx_donate_donor_first_name" value="" size="20" data-validate="required" id="text_dgx_donate_donor_first_name" class="text-box">
</div>

When I select the first item inside the div, it wraps the label around the _dgx_donate_donor_first_name-error-message div. If I say to choose the second element, it picks the input field. I want to use the text in the middle. My jQuery currently is:

$('#dgx-donate-container .text-input-section').each(function(){
  var c = 'text'+$(this).find('input[type="text"]').attr('name');
  $(this).find('input[type="text"]').attr('id', c).addClass('text-box');
  $(this).find(':first-child:not(#donation_header)').next().wrap('<label for="'+c+'" />');
});

Not pretty, but so far it seems to work. (I think I will also need to change the ID, but since I am only using the label for styling purposes, I think I should be ok for now.)

Any suggestions on how I would select the text? The format for each of the fields is exactly the same as this one.

Upvotes: 4

Views: 652

Answers (2)

Michael Doye
Michael Doye

Reputation: 8171

Use wrapInner, then re-add the other nodes:

$('#dgx-donate-container .text-input-section').each(function(){
    var c = 'text'+$(this).find('input[type="text"]').attr('name');
    $(this).find('input[type="text"]').attr('id', c).addClass('text-box');
    firstDiv = $(this).children('div:first');
    input = $(this).children('input');
    $(this).wrapInner('<label for="'+c+'" />')
    .prepend(firstDiv)
    .append(input);
});

Example Fiddle

Upvotes: 1

Kevin Heidt
Kevin Heidt

Reputation: 1155

$(function(){
    var div = $("#_dgx_donate_donor_first_name");
    var txt = $.trim(div.text());
    var txtNodes = div.contents().filter(function(){
        return this.nodeType === 3;
    }).remove();
    //console.log(txtNodes);
    //div.text("");    //don't do this, it will empty your div
    var input = div.find("input");
    var name = input.attr("name");
    var lbl = $("<label for='" + name + "'>" + txt + "</label>");
    lbl.insertBefore(input);

});

jsfiddle example

Upvotes: 1

Related Questions