Reputation: 2568
I have a form like the following and I want when the user fill an input text then automatically add another one input text and this action keep going.
The html example is:
<form method="post" action="http://localhost/save" class="save">
<fieldset>
<div>
<label>Text 1:</label><br>
<input type="text" value="" name="text1" id="text" class="input-tags">
</div>
<div>
<label>Text 2:</label><br>
<input type="text" value="" name="text2" id="text" class="input-tags">
</div>
<div>
<input type="submit" value="Save" class="elgg-button elgg-button-submit">
</div><!-- developers:end forms/application_description/save -->
</fieldset>
</form>
How can do this with jQuery?
So, the question in less words is that:
How I can show the text2
only when text1
is filled?
Upvotes: 0
Views: 180
Reputation: 1754
Yes, you can dynamically add fields to a form or a whole swath of HTML of your choice. The jQuery functions you need to look at are prepend, prependTo, append, or appendTo. They all do basically the same thing in slightly different ways.
You can keep a variable with the count of the text fields created and increment it each time you add one. If you add an id attribute to your div's it would be easier. For example, in div surrounding your submit button, you added an id like this:
<div id="submit-div">
You could say something like:
function addField() {
n++;
'<div><label>Text ' + n + ': </label><input type="text" name="text' + n + '" class="input-tags"></div>'.prependTo('#submit-div');
}
How and when you call this function is up to you but you could attach it to the blur event of the last input field. Then when you create the new one, you could remove the event handler from the previous input field.
Upvotes: 1
Reputation: 2983
something like this would work. Its pretty rough but ive tested and it works fine
$(document).ready(function(){
$("#testForm").append($("<input type='text'/>"));
$("#testForm").on("blur", 'input', function(){
$("#testForm").append($("<input type='text'/>"));
});
});
Heres a link to my fiddle. You can branch off and have a play with it.
http://jsfiddle.net/ricobano/bxEAb/
Upvotes: 2