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)
}
$(':checkbox').prop("id", function( i ){
return i;
});
$(':checkbox').each(function( i ){
this.id = i;
});
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)
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 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)
})