chromedude
chromedude

Reputation: 4302

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>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 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?

Upvotes: 3

Views: 187

Answers (2)

aligray
aligray

Reputation: 2832

An alternative method:

$('.inputDrop li').live('click', function() {
    var li = $(this);
    var currentOption = li.html();
    li.parent().prev('.dropInput').val(currentOption);
});

Upvotes: 1

alex
alex

Reputation: 490213

$(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).

Upvotes: 3

Related Questions