Why does this jQuery not embed the HTML <li> value in the <input>?
I have this HTML:
<div>
<input type="text" class="dropInput">
<ul class="inputDrop">
<li>Hello</li>
<li>Goodbye</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 do this so that when you click on one of <li>this value is inserted into <input>immediately before the list, but this is not done. Any reason this doesn't work?
+3
2 answers
$(this)will refer to the item li, 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 useful to declare variables with var, otherwise they become properties of a global object ( windowin a browser environment).
+3