简体   繁体   中英

How to set attribute for id

Here is my Html part

<input type="text" class="demo" id="" value="" />
<input type="text" class="demo" id="" value="" />
<input type="text" class="demo" id="" value="" />
<input type="text" class="demo" id="" value="" />
<input type="text" class="demo" id="" value="" />

My Jquery part

$( ".demo" ).attr( "id", "sample_1" );

However,am getting same id for all the inputs.

Now i want to increment the id as sample_2, sample_3...for n number of input's.

How, can I do it???

You can pass a function to attr instead of a static value:

$('.demo').attr('id', function (i) {
    return 'sample_' + (i + 1);
});

Try this

Demo

    $( ".demo" ).each(function(index, el){

$(this).attr( "id", "sample_"+(index+1) );
});

May be this should help

var idNumber=-1;
$('.demo').each(function(){
idNumber+=1;
$(this).attr("id",idNumber);
});

This will do ya!

<script type="text/javascript">

setTimeout(function () {

    var inputs = document.body.querySelectorAll('inputs[type="text"]');

    for (var i = 0; i < inputs.length; i++) {

        inputs[i].id = 'sample_' + (i + 1);
    };

}, 100);

<input type="text" class="demo" />
<input type="text" class="demo" />
<input type="text" class="demo" />
<input type="text" class="demo" />
<input type="text" class="demo" />

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