Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
725 views
in Technique[技术] by (71.8m points)

jquery - Use Javascript to create dynamic input id

I want to use javascript to create <input/> tags with a dynamic id (name attribute will be the same) depending on the order in which they appear.

I have the first <input/> tag in plain html and a div that should append a new <input/> with an incremented id when clicked:

<input type="text" name="1" id="1" />
<div class="add_new" onClick="add_new_input()">+</div>

Now, the javascript needs to count the amount of <input/>s currently being displayed (count) and use that amount to generate a dynamic id (count+1).

Therefore if the <div class="add_new"><.. is clicked twice, the output should be as follows:

<input type="text" name="1" id="1" />
<input type="text" name="2" id="2" />
<input type="text" name="3" id="3" />

If I append the new <input/> tag in my form using jquery's append(), would this add to the previously appended <input/>s? Or would I need to append one <input/>, then two, then three, etc?

Also, how can I use javascript to count the amount of <input/>s currently being displayed?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I had used script which is fit in your requirement .

Html:

<h2><a href="#" id="addScnt">Add Another Input Box</a></h2>

<div id="p_scents">
    <p>
    <label for="p_scnts">
        <input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" />
    </label>
    </p>
</div>

Javascript :-

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

    $('#addScnt').live('click', function () {
    $('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
    i++;
    return false;
    });

    $('#remScnt').live('click', function () {
    if (i > 2) {
        $(this).parents('p').remove();
        i--;
    }
    return false;
    });
});

working demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...