Toni Au Toni Au - 1 year ago 67
HTML Question

Access dynamic value to delete object key

I am adding items to an object and I need to be able to delete them.

<div class="list">
<span class="itemName">Item Name</span>
<a href="#" class="expand"></a>

<ul class="options">
<h5> Options </h5>
<li><a href="#" class="add">Add Item</a></li>
<li><a href="#" class="delete">Delete Item</a></li>

var tableData = {};

$(".delete").click(function() {
var tmp = $(this).parent().parent().parent().next().val();
delete tableData[tmp];

I need to get the "Item Name" because it is the key for the object I need to delete. Am I on the right track here?

Answer Source

Firstly you can use closest() instead of multiple chained parent() calls. Secondly, next() looks for siblings, yet you need to find .itemName which is a child so you need to use find(). Finally, only form inputs have a value which can be retrieved via val(). In this case you would need text() or html(). Try this:

$(".delete").click(function() {
    var tmp = $(this).closest('.list').find('.itemName').text();
    delete tableData[tmp];

Also note that your closing bracket/brace was the wrong way around. It should be }), not )}.

Working example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download