如何检查是否设置了相应的复选框数量数组值?

时间:2017-06-07 15:31:49

标签: javascript php html arrays checkbox

我正在尝试制作购物页面。我保留了选择的复选框和数量的数字类型字段。由于复选框是数组,我把数量字段也作为一个数组...我知道我们可以用检查方法检查复选框状态,现在我想要实现的是获取相应的数量值和将它存储在可变的会话中。

<?php
session_start();
if(isset($_POST['sub'])){
    $_SESSION['cbb']=$_POST['cb'];
    if(isset($_POST['qnty'])){
    $_SESSION['qtty']=$_POST['qnty'];
    header("location:userlogin.php");
    }
}
?>
<html>
<head>
</head>
<body topmargin="20">
<font color='#7FFF00'>
 <h1 align='center'>ONLINE SHOPPING</h1>
</font>
<form name="onshop" align="right" action="<?=$_SERVER["PHP_SELF"]?>" 
method="post" onsubmit="return validate()">
<input type="submit" value="Add to cart" name="sub" style="background-
color:#7FFF00" />
<input type="reset" value="Reset" style="background-color:#7FFF00"/>
<?php
$db=mysqli_connect("localhost","root","","onlineshop");
if(!$db){
    echo "Connection failure.";
}
$sql="SELECT * FROM stock";
$result=mysqli_query($db,$sql)or die("Invalid query ".mysqli_error($db));
echo "<TABLE width=50% height=70% align='center'>";
echo "<TR><TH>ITEM NAME</TH><TH>PRICE</TH><TH>IMAGE</TH><TH>Do you like?
</TH><TH>QUANTITY</TH></TR>";
while($myrow=mysqli_fetch_array($result))
    {
        echo "<TR><TD align='center'>";
        echo $myrow["item"];
        echo "</TD>";
        echo "<TD align='center'>";
        echo $myrow["price"];
        echo "</TD>";
        echo "<TD align='center'>";
        $image=$myrow["image"];
        echo '<img height="100" width="100" src="data:image/jpeg;base64,'.base64_encode( $image ).'"/>';
        echo "</TD>";
        echo "<TD align='center'>";
        $itm_id=$myrow["id"];
        echo "<input type='checkbox' name='cb[]' value='$itm_id'>";
        echo "</TD>";
        echo "<TD align='center'>";
        echo "<input type='number' name='qnty[]' value='1' max='50' 
min='1'>";
        echo "</TD>";
        echo "</TR>";
    }   
echo "</TABLE>";

mysqli_close($db);  

?>

</form>

<script type="text/JavaScript">
function validate(){
    var count=0;
    var i;
    var cbelements = document.getElementsByName("cb[]");

    if(count==0){
        for(i=0;i<cbelements.length;i++){
            if(cbelements[i].checked){
                count++;
            }
        }
        if(count<1){
            alert("Select atleast 1 item.");
            return false;
        }
    }
}
</script>
</body>
</html>
  

onchange 事件无论如何都可以有用吗?还是关联数组

0 个答案:

没有答案