Forum Moderators: coopster

Message Too Old, No Replies

Mulitiply the values entered by user using java script and php

         

ravii

9:14 am on Apr 24, 2009 (gmt 0)

10+ Year Member



hello,

here is example with 3 cells

when the user click on the ANSWER button then the values should get multiply and view the answer
but the problem is i can't get the value which i entered in the text box

please tell me what the wrong is

here is the code

<html>
<head>

<script type="text/javascript">
function cell(r)
{
var x=document.getElementById('myTable')
var y = x.rows[r].cells[0].innerHTML;
var z = x.rows[r].cells[1].firstChild.value;

var q=y*z;
alert(y);
alert(z);
alert(q);
}
</script>
</head>

<body>

<table id="myTable" border="1">
<?php
for($r=1;$r<=3;$r++)
{
echo'<tr>
<td>10</td>
<td><input type="text" id="txt"/></td>
<td><input type="button" onClick="cell('.$r.')" value="Answer"></td>
</tr>';
}
?>

</table>
<br />
</body>
</html>

rocknbil

4:20 pm on Apr 24, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Try adding a value attribute to the text field?

Second, if you generate a loop, all your fields will be named and ID'd as "txt". ID's need to be unique (and you need a name attribute to read them via get or post:)

for($r=1;$r<=3;$r++) {
$anscell='ans' . $r;
$txtname='txt' . $r;
echo'<tr>
<td id="'.$anscell.'">10</td>
<td><input type="text" name="'.$txtname.'" id="'.$txtname.'" value=""></td>
<td><input type="button" onClick="cell('.$r.')" value="Answer"></td>
</tr>';
}

Your Javascript is also going "the hard way around the fence." Since you're dynamically building these, just assign ID's to the elements you want to use (see "$anscell" above) and do this:

<script type="text/javascript">
function cell(r) {
var anscell = 'ans'+r;
var txtfield = 'txt'+r;
if (document.getElementById(anscell) && documentgetElementById(txtfield)) {
var x = parseInt(document.getElementById(anscell).innerHTML);
var y = parseInt(document.getElementById(txtfield).value);

var q=x*y;
alert(q);
}
</script>

I've used parseInt() because often text inputs get interpreted as strings which gives you 23 in the case of 2+3, you may need to play with that if there are decimal values. But if you're always multiplying, you may be able to eliminate any of the parse methods.

Untested; if it doesn't properly get the innerHTML value, I'd suggest using hidden fields instead.

rocknbil

1:57 am on Apr 25, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



checking in, SORRY I have an error here, missing DOT between "document" and "getElementById", should be

if (document.getElementById(anscell) && document.getElementById(txtfield)) {