Search code examples
jqueryhtmlfor-loopinputkeyup

Creating dynamic names to inputs created by jquery append


I have a HTML like below:

NOF:
<input type="text" class="nof" />

<div class="myfld">
</div>

And the jquery:

html = '';
var html = 'Name : <input type="text" name="ss" />';
var html = html + 'Email : <input type="text" name="email" />';

$('.nof').keyup(function(){
$('.myfld').empty();
    nof = $('.nof').val();
    for(var x = 0;  x < nof; x++) {
        $('.myfld').append(html);
    }
});

When I key up, it's creating the input fields dynamically and upto this point working nicely. But the problem is all the fields created are having same name as ss and email. So how can I make these names as ss1,email1,ss2,email2 and so on?

DEMO


Solution

  • Try something like this

    $('.nof').keyup(function(){
    $('.myfld').empty();
        nof = $('.nof').val();
        for(var x = 0;  x < nof; x++) {
            $('.myfld').append('Name : <input type="text" name="ss_'+x+'" />Email : <input type="text" name="email_'+x+'" /><br/>');
        }
    });
    

    everytime you append the inputs you also change the name of the inputs so for 3 inputs you have something like ss_0/email_0, ss_1/email_1, ss_3/email_3