user2424221 user2424221 - 3 years ago 82
HTML Question

How to multiply 2 td in Javascript?

I have a table where one td gets 1 if a checkbox is checked and I would like to multiple this td with another and display it in a third one.

See the html here:

<div>
<input type="checkbox" id="fut1">check</input>
</div>
<table border="1" cellpadding="10" id="countit">
<tr>
<td id="td1"></td>
<td id="td2">5000</td>
<td id="td3"></td>
</tr>
</table>


And here is the js:

$('#fut1').change(function () {
if ($(this).is(":checked")) {
$('#td1').text('1');
} else {
$('#td1').text('0');
}
});

$('#td1').change(function () {
var me = $('#td1').value;
var ar = $('#td2').value;
var sum = me * ar;
$('#td3').text(sum);
});

Answer Source
$('#td1').change(function () {  // <--- td elements don't have a change event listener/handler
    var me = $('#td1').value;   // <--- td elements don't have a value
    var ar = $('#td2').value;   // <--- td elements don't have a value
    var sum = me * ar;
    $('#td3').text(sum);
});

If you want to do it this way:

$('#fut1').change(function () {
    if ($(this).is(":checked")) {
        $('#td1').text('1');
    } else {
        $('#td1').text('0');
    }
    callTdChange();
});

function callTdChange() {
    var me = parseInt($('#td1').text());
    var ar = parseInt($('#td2').text());
    var sum = me * ar;
    $('#td3').text(sum);
}

Of course, the better way should be to use form elements (inputs) in the case you want to save your data to a server, or use change behaviors.

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