user3483164
user3483164

Reputation: 7

Add a label tag for each input tag dynamically for the DOM using JQuery

1.The input element's id attribute and the corresponding label element should have a for attribute. The values of these two attributes must be equal. For this, needs to add a label tag for each input tag for the DOM using JQuery.

Example:

First Name :<input type="text" name="first_name" id="firstName" value="" maxlength="100" />

needs to add

<label for="firstName">First Name : <label> 
<input type="text" name="first_name" id="firstName" value="" maxlength="100" />

2. Or this will also be fine

<label> First Name : <input type="text" name="first_name" id="firstName" value="" maxlength="100" /></label>

Thank you so much in advance :) :)

Upvotes: 0

Views: 3252

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

You can use the wrap() like

jQuery(function ($) {
    $('input').wrap(function () {
        return $('<label />', {
            for: this.id
        }).append(this.previousSibling)
    })
})

Demo: Fiddle


Or use .before() like

jQuery(function ($) {
    $('input').before(function () {
        return $('<label />', {
            for: this.id
        }).append(this.previousSibling)
    })
})

Demo: Fiddle

Upvotes: 1

Related Questions