sajid
sajid

Reputation: 893

How to traverse dom tree from a list of elements

I have HTML snippet which looks like this. I generate this snippet multiple times form the backend. When I click the Save button, I catch which Save button was clicked using $(this) selector. Now I want to grab the attribute item-id of the corresponding Save button. I have the following jquery code snippet. But it does not work. I have tried to look but I don't know where the error is.

<td><input type="text" size="10" value="val1" item-id="id1"></td>
<td><input type="text" value="val2" size="4"></td> 
<td>
  <button class="btn btn-primary save-btn">Save</i></button>
</td>

Here is the jquery snippet

 $(".save-btn").click(function(){
        var ems = $(this).parent().siblings();
       var item_id = ems[0].child().attr("item-id");
   }

Upvotes: 2

Views: 199

Answers (2)

Ivan Karaman
Ivan Karaman

Reputation: 1234

better replace item-id="id1" to data attribute html5 data-id="id1" then replace code attr('item-id') to data('id')...

$(document).on('click','.save-btn', function(){
        var ems = $(this).parent().siblings(),
            item_id = ems.eq(0).children('input').attr("item-id");
             alert(item_id);
   });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
<td><input type="text" size="10" value="val1" item-id="id1"></td>
<td><input type="text" value="val2" size="4"></td> 
<td>
  <button class="btn btn-primary save-btn"><i>Save</i></button>
</td>
    </tr>
  </table>

Upvotes: 2

rahulparekh
rahulparekh

Reputation: 36

click doesn't work on dynamically added elements.You need to use on('click'). Also there is no method .child() so you need to use .children().first().

This is the corrected code:

$(document).on('click', '.save-btn', function(){
   var ems = $(this).parent().siblings();
   var item_id = ems.children().first().attr("item-id");
});

// The text
var text="";
text += "<td><input type=\"text\" size=\"10\" value=\"val1\" item-id=\"id1\"><\/td>";
text += "<td><input type=\"text\" value=\"val2\" size=\"4\"><\/td> ";
text += "<td>";
text += "  <button class=\"btn btn-primary save-btn\">Save<\/i><\/button>";
text += "<\/td>";


// Adding the text to html
$('body').html(text);


$(document).on('click', '.save-btn', function(){
    var ems = $(this).parent().siblings();
    console.log(ems);
    var item_id = ems.children().first().attr("item-id");
    alert(item_id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 2

Related Questions