简体   繁体   中英

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?

$(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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM