Use Javascript To Create Dynamic Input Id
I want to use javascript to create tags with a dynamic id (name attribute will be the same) depending on the order in which they appear. I have the first
Solution 1:
I had used script which is fit in your requirement .
Html:
<h2><ahref="#"id="addScnt">Add Another Input Box</a></h2><divid="p_scents"><p><labelfor="p_scnts"><inputtype="text"id="p_scnt"size="20"name="p_scnt"value=""placeholder="Input Value" /></label></p></div>
Javascript :-
$(function () {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').live('click', function () {
$('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
i++;
returnfalse;
});
$('#remScnt').live('click', function () {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
returnfalse;
});
});
Solution 2:
Try like
functionadd_new_input() {
var last_id = $('input[type="text"]:last').attr('id');
last_id++;
$('input[type="text"]:last').append('<input type="text" name="'+last_id+' id="'+last_id+'">');
}
Solution 3:
Try this
functionadd_new_input(){
var lastControlId = $('input:text:last').attr('id');
if(!lastControlId){
lastControlId = parseInt(lastControlId,10) + 1;
$('#containerDiv').append('<input type="text" name="'+ lastControlId +' id="'+ lastControlId +'">');
}
}
Solution 4:
jQuery('#select').change(function () {
varval = jQuery(this).val();
var innerhtml = '';
for (var i = 0; i < val; i++) {
innerhtml += "<input type='text' id='" + (i + 1) + "' name='" + (i + 1) + "'size=50> </br>";
}
jQuery('#textbox_div').html(innerhtml);
});
Solution 5:
$( "input" ).each(function( index ) {
$(this).attr('id', 'item-' + index);
});
This should alter all inputs with id of "item-[index number]".
But you should throw in .class identification to selector so this doesn't apply to all.
Post a Comment for "Use Javascript To Create Dynamic Input Id"