[英]how to fetch values from array input in javascript
How do I properly fetch values from array in javascript: 如何正确地从JavaScript中的数组中获取值:
<html>
<head>
<script type="text/javascript">
function proc()
{
var cost = document.yoh.coz.value;
var qtybuy = document.yoh.qbuys.value;
var st = cost * qtybuy;
var tbox = document.yoh.subtotal;
if (tbox)
{
tbox.value = st;
}
}
</script>
</head>
<body>
<?php
include('conn.php');
$prodname = $_GET['prodname'];
$result = query_database("SELECT * FROM prod_table WHERE PRODUCT='$prodname'", "onstor", $link);
?>
<?php while ( $row = mysql_fetch_array($result) ) { ?>
<form name="yoh" method="get">
Product id: <input type="text" name="prodid" value=""><br/>
Cost: <input type="text" name="coz" value="<?php echo $row['S_PRICE']; ?>"><br/>
Quantity to buy:<input type="text" name="qbuys" value="" onkeyup="proc();"></br>
Subtotal:<input type="text" name="subtotal" value=""></br>
</form>
</body>
<?php } ?>
</html>
As you can see this program will just multiply the 2 values. 如您所见,该程序只会将2个值相乘。 One of the values would be fetched from the database, and the other comes from the user.
其中一个值将从数据库中获取,另一个则来自用户。 If I do it this way, I don't get any results:
如果以这种方式进行操作,则不会获得任何结果:
<html>
<head>
<script type="text/javascript">
function proc()
{
var cost = document.yoh.coz[].value;
var qtybuy = document.yoh.qbuys[].value;
var st = cost * qtybuy;
var tbox = document.yoh.subtotal[];
if (tbox)
{
tbox.value = st;
}
}
</script>
</head>
<body>
<?php
include('conn.php');
$prodname = $_GET['prodname'];
$result = query_database("SELECT * FROM prod_table WHERE PRODUCT='$prodname'", "onstor", $link);
?>
<?php while ( $row = mysql_fetch_array($result) ) { ?>
<form name="yoh" method="get">
Product id: <input type="text" name="prodid[]" value=""><br/>
Cost: <input type="text" name="coz[]" value="<?php echo $row['S_PRICE']; ?>"><br/>
Quantity to buy:<input type="text" name="qbuys[]" value="" onkeyup="proc();"></br>
Subtotal:<input type="text" name="subtotal[]" value=""></br>
</form>
</body>
<?php } ?>
</html>
Do I need to include the index manually? 我需要手动添加索引吗? What do I need to do to achieve the same results when using arrays.
使用数组时,我需要怎么做才能获得相同的结果。
您可以使用名称值:
cost=document.yoh.elements['coz[]'].value;
You need to iterate through the arrays. 您需要遍历数组。 To iterate through an array (or object) in JavaScript:
要遍历JavaScript中的数组(或对象):
for (key in arr){
// The key will be set to each key in the array (arr)
// The value at that key will be arr[key] (like always)
}
I'm not entirely sure what your goal is, but in general, know that the "[]" syntax is PHP only, JavaScript treats it as any other name (and possibly as a syntax error). 我不能完全确定您的目标是什么,但总的来说,您知道“ []”语法仅是PHP,JavaScript会将其视为任何其他名称(并且可能会视为语法错误)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.