根据select选项值填充html代码块

时间:2013-05-09 16:05:18

标签: jquery

我有一个选择框,用户可以在其中选择要注册的人数。例如,如果选择4,则表单下方会显示4个人注册区域:

jQuery的:

var person = '<div class="reg-person"><span class="person">Person 1</span><div class="field"><label for="name">name</label><input type="text" id="name" name="name" /></div><div class="field"><label for="company">company</label><input type="text" id="company" name="company" /></div><div class="field"><label for="email">email address</label><input type="text" id="email" name="email" /></div><div class="field"><label for="contact">contact number</label><input type="text" id="contact" name="contact" /></div></div>';

            var peopleDisplayed = 0;

            $('.places-req').change(function() {
                if(peopleDisplayed == 0) {
                    peopleDisplayed = ($(this).val());
                    numberPeople = ($(this).val());
                    for(var i = 1 ; i <= numberPeople ; i++){
                        $('#register').prepend(person);
                    }
                } else {
                    var peopleDiff = ($(this).val() - peopleDisplayed);
                    if (peopleDiff > 0) {
                        for(var i = 1 ; i <= peopleDiff ; i++){
                            $('#register').prepend(person);
                        }
                    } else if (peopleDiff < 0) {
                        var diff = -peopleDiff;
                        for(var i = 1 ; i <= diff ; i++){
                            $('#register').children('div.person').last().remove();
                        }
                    }
                    peopleDisplayed = ($(this).val());
                }

            });

html是:

<form id="register" action="/event/scripts/register.html" method="post">


                        <div class="submit-field">
                            <input type="hidden" value="1" id="event" name="event" />
                            <input type="submit" value="" />
                        </div>
                        <p>* Please note that we will not pass your details to a third party.</p>
                    </form>

我的问题是如何修改代码,以便每个人都显示人1,人2等...此时他们都显示为人1.我还需要使用此编号来使用表单字段名称,以便它们不同,name1,name2等..

2 个答案:

答案 0 :(得分:2)

你需要在i循环中使用for来拥有Person1,Person2 ......

$('#register').prepend('<div class="reg-person"><span class="person">Person '+i+' </span><div class="field"><label for="name">name</label><input type="text" id="name" name="name" /></div><div class="field"><label for="company">company</label><input type="text" id="company" name="company" /></div><div class="field"><label for="email">email address</label><input type="text" id="email" name="email" /></div><div class="field"><label for="contact">contact number</label><input type="text" id="contact" name="contact" /></div></div>');
 -----------------------------------------------------------------------------^

答案 1 :(得分:1)

我不知道如何发表评论,但答案就是这个小提琴

http://jsfiddle.net/CQg8L/

parseInt(parseInt(peopleDisplayed)+i)