I'm trying to add extra input fields to my HTML form as they are needed. Here's my code:
My code
JS
$(document).ready(function(e) {
var i = $('.form-inputs input').size() + 1;
$('.section-topic-field').last().bind('keyup', function(e) {
if($(this).val() != "") {
var html_new_field = '<input name="txtTopicName' + i + '" class="section-topic-field" type="text" onfocus="this.value=\'\'" placeholder="topic name #' + i + '" /><br />';
$('.form-inputs').append($(html_new_field).fadeIn('slow'));
i++;
}
});
});
HTML
<input name="txtSection" type="text" onfocus="this.value=''" placeholder="sections"/><br/>
<div class="form-inputs">
<input name="txtTopicName1" class="section-topic-field" type="text" onfocus="this.value=''" placeholder="topic name #1"/><br />
</div>
<!--<button class="btn btn-mini btn-primary" type="submit">Create</button>-->
</form>
The problem
However, the function ALWAYS triggers on the first input field, so typing ,for example, 4 letters in the first input field, will generate 4 input fields. And when you then type something in the actual last input field (the 4th in this case) nothing happens. So for some reason $('.section-topic-field').last()
always selects the first input field.
I also tried the :last
selector and the :last-child
, but result is just the same
Any help?
Thanks!