views:

45

answers:

2

Hello,

How do I reorder my inputs when my function is called?

ie: When the a2 delete button is clicked now I have a1, a3, and a4 I want to reorder this so that it is a1, a2 (was a3), and a3(was a4). I know how to do this manually, but how do I write it dynamically?

Script:

    
    $(function(){
        $('.deleteMe').click(function(){
            $(this)
                .parent()
                .parent()
                .remove();
            //rename the attribute
            ???
            $('#a3').attr('name', 'a2') //a3 becomes a2
            $('#a4').attr('name', 'a3') //a4 becomes a3
            return false;
        });
    });
    

Here is the HTML:

<form name="myform" id="myform" method="post">
<table>
<tr>
  <td><input type="text" name="a1" id="a1" /></td>
  <td><input type="button" class="deleteMe" name="deleteMe" id="deleteMe" value="a1" /></td>
</tr>
<tr>
  <td><input type="text" name="a2" id="a2" /></td>
  <td><input type="button" class="deleteMe" name="deleteMe" id="deleteMe" value="a2" /></td>
</tr>
<tr>
  <td><input type="text" name="a3" id="a3" /></td>
  <td><input type="button" class="deleteMe" name="deleteMe" id="deleteMe" value="a3" /></td>
<tr>
</tr>
  <td><input type="text" name="a4" id="a4" /></td>
  <td><input type="button" class="deleteMe" name="deleteMe" id="deleteMe" value="a4" /></td>
</tr>
</table>
</form>
+1  A: 

If you can easily select all your inputs, just loop through all of them and rename.

container = $(this).parent().parent().parent();
// (delete input)
$(container).find("input:text").each(function(index) {
    $(this).attr("name", "a" + index);
});

However the question arises, why do you need to do this? You could just give all of them the same name, and most server site stuff should be able to get you a list of values.

Matti Virkkunen
Matti, thanks a bunch!!!In the program that I am working on I actually have an input text and checkbox next to each other. I would not know which checkbox belongs to what if they are not all check.
nolabel
+1  A: 

Add a class="renameable" onto each of those input fields, and then do something like this:

$(function(){
  $('.deleteMe').click(function(){
    $(this).parent().parent().remove();
    $('#myForm').find('.renameable').each(function(i){
      $(this).attr('name', 'a'+i);
    });
    return false;
  });
});
James Skidmore