javascript - Increment elements ID - Stack Overflow

but with this code all checkbox elements have the same id...var count;var length = $('input[type=

but with this code all checkbox elements have the same id...

var count;
var length = $('input[type=checkbox]').length
for(count=1;count<=length;count++){
    $('input[type=checkbox]').attr('id',count)
}

but with this code all checkbox elements have the same id...

var count;
var length = $('input[type=checkbox]').length
for(count=1;count<=length;count++){
    $('input[type=checkbox]').attr('id',count)
}
Share Improve this question edited Oct 22, 2015 at 23:21 Roko C. Buljan 207k41 gold badges328 silver badges340 bronze badges asked May 4, 2013 at 15:29 pouyapouya 431 silver badge9 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 4

Set elements ID using .prop() or .attr()

$(':checkbox').prop("id", function( i ){
    return i;
});

jsBin demo

Set elements ID using .each()

$(':checkbox').each(function( i ){
    this.id = i;
});

jsBin demo

Both examples return:

<input id="0" type="checkbox">
<input id="1" type="checkbox">
<input id="2" type="checkbox">
<input id="3" type="checkbox">

if you want to start from 1 just use:

this.id = i+1;

Since numerical ID is not supported in non HTML5 (older) browsers, add any string prefix to the ID number like "el"+ (i+1)

$('input[type=checkbox]').prop('id', function(i) {
     return ++i;
});

Use each() to iterate through elements returned by selector and assign ids. Numeric id is generally not considered a good practice you prefix of postfix with some string.

 $('input[type=checkbox]').each(function(i){
   $(this).attr('id',"id_"+i)
 })

Use .each() instead:

$('input[type=checkbox]').each(function(i) {
    // i is the 0-based index of this element in the matched set
    $(this).prop('id', i); 
});

use this:

$(document).ready(function() {
   var count = 1;
   $("input[type='checkbox']").each(function(index,domobj) {
      $(domobj).prop("id",count++);
   });
});

use .prop() when your jquery is 1.6+
use .attr() when your jquery is 1.6-

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745108054a4611677.html

相关推荐

  • javascript - Increment elements ID - Stack Overflow

    but with this code all checkbox elements have the same id...var count;var length = $('input[type=

    9小时前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信