简体   繁体   中英

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 :) :)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM