Reputation: 240
Got a div whose ID="cartArea" in there I have mulitple textbox
<input type="text" id="tb_1" name="tb_1" />
<input type="text" id="tb_2" name="tb_2" />
<input type="text" id="tb_3" name="tb_3" />
and so on, there could be more or less items in the list. Beside each textbox there is a remove option. I can get the selected textbox to be removed from the container div no problem, but what I need to be able to do is then rename the remaining textboxes.
So if I remove tb_2
, I'm not left with tb_1
and tb_3
, but rather tb_1
and tb_2
Can this be done and if so how?
Upvotes: 1
Views: 6762
Reputation: 400
No need for a quirky javascript solution here.
Just do it like:
<input type="text" id="tb_1" name="tb[]" />
<input type="text" id="tb_2" name="tb[]" />
<input type="text" id="tb_3" name="tb[]" />
Server side it is accessible via $_GET['tb']
which is an array. So $_GET['tb'][0]
, $_GET['tb'][1]
and $_GET['tb'][2]
representing your data if you sent 3 inputs to the server.
Upvotes: 0
Reputation: 382686
Afer you remove, you can run this code to rename them:
$('input[id^=tb_]').each(function(i, v){ this.name = 'tb_' + i; });
Upvotes: 0
Reputation: 4139
I didn't like others responses because they either used the costly input[id^=] selector, the wordy input[type=text] selector, didn't account for i-being 0 based or didn't set the name attribute.
You can run this code after removal to rename the textboxes.
$('#cartArea input:text').each(function(i){ this.id = this.name = 'tb_' + (i + 1); });
JSFiddle: http://jsfiddle.net/HT6gS/
Upvotes: 0
Reputation: 20323
After deletion you can loop through remaining element and change there name attr
Sample HTML:
<input type="text" id="tb_1" name="tb_1" /><span>remove</span>
<input type="text" id="tb_2" name="tb_2" /><span>remove</span>
<input type="text" id="tb_3" name="tb_3" /><span>remove</span>
Sample Code:
jQuery('span').click(function(){
jQuery(this).prev().remove();
jQuery(this).remove();
jQuery('input').each(function(index){
jQuery(this).attr('name','tb_' + (index +1));
});
});
Upvotes: 0
Reputation: 148110
Put this code in some function and call that function after deleting element.
Try this, Live Demo
$('#cartArea').children('input[type=text]').each(function(){
this.name ='tb_' + eval($(this).index()+1);
//alert( this.name)
});
Upvotes: 1
Reputation: 87073
You can achieve your goal very simply like following:
$('#cartArea input[type=text]').attr('id', function(){
return 'tb_' + $(this).index(); // change id
}).attr('name', function() {
return 'tb_' + $(this).index(); // change name
});
Upvotes: 1