Question

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

Was it helpful?

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

OTHER TIPS

You can move the corresponding lines inside for loop

var html = ''; 
for (var x...) {
html = 'Name : <input type="text" name="ss' + x + '" />';

same for email

You can replace a "Salt" at each iteration like this :

html = '';
var html = 'Name : <input type="text" name="ssFOO" />';
var html = html + 'Email : <input type="text" name="emailFOO" />';
var html = html + '<br />';

$('.nof').keyup(function(){
$('.myfld').empty();
    nof = $('.nof').val();
    for(var x = 0;  x < nof; x++) {
        var newHtml = html.replace(/FOO/g, String(x));
        $('.myfld').append(newHtml);
    }
});

Demo

you can check this updated fiddle demo [http://jsfiddle.net/49gJG/7/] Demo

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