Search code examples
jquerymobilejquery-traversing

find value of nearest input field


Please help on the code in this fiddle. What I'm trying t achieve is to get the input value from a field nearest to the delete button. :

http://jsfiddle.net/w9g3e8mb/11/

 function deleteTheCtrl() {
   var ctrl_name = $(this).parent().find("div").first().find("input").first().val();
   alert("Control Name :: " + ctrl_name);     
 }

the HTML is as below:

 <ul>
 <li style="height: 200px; width:300px !important;margin-left: 30px;overflow: visible;">
    <label for="control_name">Control Name:</label>
    <div class="ui-input-text ui-body-inherit ui-corner-all ui-shadow-inset">
        <input name="control_name" id="control_name" value="Fan" type="text"/>
    </div>
    <button type="button" onclick="deleteTheCtrl()" data-ajax="false" class="ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-notext deleteCtrlLink" title="Delete Control" value="Delete Control" height="30px">Get Name</button>
 </li>
 </ul>

Solution

  • If the li will only ever have a single input in it, then:

    var ctrl_name = $(this).closest('li').find('input').val();
    

    ...but yours would work as well. The real issue is that this isn't what you expect it to be.

    To fix it, pass this into deleteTheCtrl:

    onclick="deleteTheCtrl(this)"
    

    ...and then use that argument:

    function deleteTheCtrl(btn) {
        var ctrl_name = $(btn).closest('li').find('input').val();
        // Or your: var ctrl_name = $(btn).parent().find("div").first().find("input").first().val();
    }
    

    But even better would be not using an onclick attribute at all. Instead, handle click on the list:

    $("selector for the list").on("click", "button.deleteCtrlLink", function() {
        var ctrl_name = $(this).closest('li').find('input').val();
        // Or your: var ctrl_name = $(this).parent().find("div").first().find("input").first().val();
    });
    

    Because that's a delegated handler, it works even when you add and remove list items, provided the ul or ol element you're identifying with selector for the list isn't deleted/recreated. (If it is, just hook the click further out.)