How can i get the specific value that clicked on the button using jquery

时间:2019-04-17 02:41:01

标签: jquery html

I have problem regarding getting the value on the specific table row, when I click the first button they get all the value. however when I click the second button itself value show

Goal: I want to get the value of price on specific table row.

Output

I have here the my Click function

$("button.removeorderWithCondi").on("click", function() {


     var parent = $(this).closest(".condimentParent");
     var get_parent_price  = $(this).closest("tr").find(".total").text();

     console.log(get_parent_price);


});

Problem:

Output problem

2 个答案:

答案 0 :(得分:1)

可能更好的选择是将值与按钮紧密关联,而不是依赖于可能会或可能不会更改的HTML结构。您可以为此使用data attribute。这还具有以下优点:如果格式化了显示值,则可以使用原始值。

您将看到以下内容:

$("button.removeorderWithCondi").on("click", function() {
     var price  = $(this).data("value");
     console.log(price);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<button class="removeorderWithCondi" data-value="5.00">Delete</button>

这种方法的缺点是,您必须首先重构生成表的内容

答案 1 :(得分:0)

我假设您的html表将处于此结构中,希望可以解决您的问题,谢谢

$('.getprice').click(function(e){
console.log($(this).parent().prev().text())
})
td
{
border:1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th>Price</th>
<th>Action</th>
</tr>
<tr>
<td>20</td>
<td><button class="getprice">Click</button></td>
</tr>
<tr>
<td>0.00</td>
<td></td>
</tr>
<tr>
<td>0.00</td>
<td></td>
</tr>
<tr>
<td>50</td>
<td><button class="getprice">Click</button></td>
</tr>

</tbody>

</table>