Why does this jQuery not insert the value of the HTML <li> into the <input>?
I have this HTML:
<div>
<input type="text" class="dropInput">
<ul class="inputDrop">
<li>Hello</li>
<li>G开发者_如何学编程oodbye</li>
</ul>
<input type="text" class="dropInput">
<ul class="inputDrop">
<li>Hola</li>
<li>Adios</li>
</ul>
</div>
and I have this jQuery:
$('.inputDrop li').live('click', function(){
currentOption = $(this).html();
$(this).prev('.dropInput').val(currentOption);
});
It is supposed to make it so that when you click on one of the <li>
s it's value is inserted in the <input>
just before the list, but it is not doing this. Any reason why this is not working?
$(this)
will refer to the li
element, not the parent ul
.
Try this instead...
$('.inputDrop li').live('click', function(){
var currentOption = $(this).html();
$(this).closest('ul').prev('.dropInput').val(currentOption);
});
jsFiddle.
It is also a good idea to declare variables with var
, otherwise the become properties of the global object (window
in a browser environment).
An alternative method:
$('.inputDrop li').live('click', function() {
var li = $(this);
var currentOption = li.html();
li.parent().prev('.dropInput').val(currentOption);
});
精彩评论