开发者

how to fetch values from array input in javascript

How do I properly fetch values from array in 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;开发者_如何学Go
            }
        }
    </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. 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.


You can use a name value:

cost=document.yoh.elements['coz[]'].value;


You need to iterate through the arrays. To iterate through an array (or object) in 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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜