Question

i took the code below on the internet, but i have no ideia how when i add or remove a input automatically the input's rename.

html

<input type="text" value="" id="qta_alternativas" size="4" /><div id="div_01"><a href="#" id="add">Adicionar</a></div>
        <div id="div_03">
          <div id="p_scents">
            <p>
              <input type="text" id="p_scnt" size="50" name="opcao_1" />
            </p>
          </div>
        </div>

jQuery

    $(function() {
    var scntDiv = $('#p_scents');
    var i = $('#p_scents p').size() + 1;

    $('#add').live('click', function() {
            $('<p><input type="text" id="p_scnt" size="50" name="opcao_' + i +'" /><a href="#" id="remove_opcao">Remover</a></p>').appendTo(scntDiv);
            i++;
            document.getElementById('qta_alternativas').value = i-1;
            return false;
    });

    $('#remove_opcao').live('click', function() { 
            if( i > 2 ) {
                    $(this).parents('p').remove();
                    i--;
                    document.getElementById('qta_alternativas').value = i-1;
            }
            return false;
    });

    $("input[name^=opcao_]").each(function(index) {
        this.name = "opcao_" + index;
    });

});

Example:

<input type="text" id="p_scnt" size="50" name="opcao_1" />
<input type="text" id="p_scnt" size="50" name="opcao_2" />
<input type="text" id="p_scnt" size="50" name="opcao_3" />
<input type="text" id="p_scnt" size="50" name="opcao_4" />

if i remove the input name="opcao_3", my code will get like:

<input type="text" id="p_scnt" size="50" name="opcao_1" />
<input type="text" id="p_scnt" size="50" name="opcao_2" />
<input type="text" id="p_scnt" size="50" name="opcao_4" />

but i want when i remove my code get like:

<input type="text" id="p_scnt" size="50" name="opcao_1" />
<input type="text" id="p_scnt" size="50" name="opcao_2" />
<input type="text" id="p_scnt" size="50" name="opcao_3" />

How can i do that?! Someone can help me?

Thanks!!

Was it helpful?

Solution 2

I added this code to my code.. and it is working!!

$(document).delegate('a','click',function()
{
    $( this ).parent('p').remove();
});

OTHER TIPS

Add this code to the end of the remove click handler...

$("input[name^=opcao_]").each(function(index) {
    this.name = "opcao_" + index;
});

It will go through all the inputs with a name attribute that begins with "opcao_" and rename them using an index.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top