Geek asks and answers

    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
    javascript jquery html
    chromedude Jun 15 '11 at 1:43
    source share
    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
    alex Jun 15 '11 at 1:47
    source share

    Alternative method:

    $('.inputDrop li').live('click', function() {
        var li = $(this);
        var currentOption = li.html();
        li.parent().prev('.dropInput').val(currentOption);
    });
    
    +1
    aligray Jun 15 '11 at 1:59
    source share

    More articles:

    • Make Plone Compliant 403 Forbidden Errors - http-status-code-403
    • Can concurrntHashMap guarantee true thread safety and concurrency at the same time? - java
    • struts2 jstl iterator tag - java
    • jQuery: I cannot set a value in a loop with a dynamic value - javascript
    • Tracking the currently selected index path and the previously selected index path - objective-c
    • Fixed array segmentation error PHP 5.3.5 - arrays
    • C, which can receive shutdown / shutdown requests linux / upstart / ubuntu - c
    • Does auto scaling work fine on phone screens, but not on tablets? - android
    • How to write a tree structure to disk (VBA without serialization) - vba
    • Change values ​​from array during iteration - arrays

    All Articles

    Geek-Ask | 2020