I have dynamically generated HTML table that I want to use with JQuery. It looks kind of like this, only with more <tr>
elements.
<table>
<tr>
<td class="name"> Apples </td>
<td class="value"> 2.33 </td>
<td class="amount"> <input type="text"></td>
</tr>
</table>
The script I'm writing would take whatever's in the text input field, multiply it by the float specified in the value td
and output it. However, I have problems getting to that <td>
using JQuery.
I tried something like
parseFloat($(".amount input").parent().siblings($("td.value")).text())
to get the value, but it doesn't work - it seems to be trying to multiply it by every element regardless of the class. I tried a <tr>
where the only data was integers...
2013-8-28 | 2.1 | 20
...and it spat out 4026. I have no idea why.
So, the question remains: how do I get the contents of the <td>
with the class value
starting from the input
on the same <tr>
?
Try this:
$(document).ready(function(){
$('input').on('blur', function(){
alert($(this).val() * $(this).parent().siblings('.value').text());
});
})
怎么样
$(".amount").parent().find('.value').text();
try
HTML
<table>
<tr>
<td id="val1" class="name"> Apples </td>
<td id="val2" class="value"> 2.33 </td>
<td class="amount"> <input type="text"></td>
</tr>
</table>
JavaScript
function getvalue()
{
var name = (document.getElementById('val1').innerText || document.getElementById('val1').textContent);
var value = parseFloat(document.getElementById('val2').innerText || document.getElementById('val1').textContent);
}
you can try
$('.amount').each(function(){
var $this = $(this), amount = parseFloat($this.find('input').val()) || 0, rate = parseFloat($this.prev().text()) || 0;
console.log(amount * rate)
})
This should also work
$('input').on('blur', function(){
alert($(this).val() * $(this).parent().siblings('.value').text());
});
Working fiddle here
The selector in your siblings()
function is wrong. Try this:
parseFloat($(".amount input").parent().siblings(".value").text())
Use :
$('input').on('blur', function(){
var value = $(this).closest("tr").siblings(".value").text();
});
There are many options to do :
$(".amount input").parent().prev("td.value").text() //good to use
or
$(".amount input").parent().siblings("td.value").text()
or
$(".amount input").parent().parent().find("td.value").text()
Full working demo
I have done with keyup event you can however you want , FIDDLE
jQuery(function(){
$('.amount input').keyup(function(){
var input_value = this.value;
var values = $(this).parent().prev().text();
alert(input_value * values);
})
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.