Reputation: 20163
I am trying to build a custom keywords field for my site,
The thing is I have a input div holder where I append inputs by clicking a button, but i check
$('div inputs').last().val().length < 3
if its smaller than 3 i shake the input, else:
$('div inputs').last().after('<input type="text" />')
Problem is that:
$('div inputs').last().val()
returns allways the first input value, what am i doing wrong?
Upvotes: 1
Views: 70
Reputation: 137350
At the beginning of your script you select inputs
:
var inputs = $('#keysInput input');
After that you use that specific value set when the script is first run, which does not contain newly created fields. In other words: you work on inputs
containing only one field (initial one).
The solution is to simply re-assign value (list of selected inputs) to this variable.
Upvotes: 0
Reputation: 34107
Something like this: demo http://jsfiddle.net/pVJXM/5/
Behaviour: every time you enter3
character and more and hit +
click you will get an append an inout at the end.
I used var inputs = $('#keysInput input:last');
instead of using .last()
multiple time :) that will do the trick for you.
Hope it helps,
code
var cont = $('#keysInput');
var addBtn = $('#addKey');
$('body').on('keydown','#keysInput',function(e){
});
$('body').on('click','#addkey',function(e){
var inputs = $('#keysInput input:last');
if(inputs.val().length < 3){
inputs.effect("shake", { times:1, distance: -5 }, 300);
}else{
console.log(inputs.last().val());
inputs.after('<input type="text" placeholder="type another keyword" />');
}
})
Upvotes: 1
Reputation: 12128
You have cached your inputs on top, so you are always using the same set of input controls - one.
Define your inputs variable within callback and it will work:
$('body').on('click','#addkey',function(e){
var inputs = $('#keysInput input');
if(inputs.last().val().length < 3){
$('#keysInput input').last().effect("shake", { times:1, distance: -5 }, 300);
}else{
console.log(inputs.last().val());
$('#keysInput input').last().after('<input type="text" placeholder="type another keyword" />');
}
})
Upvotes: 2