如果没有从 dsiplayed 项目列表中选择项目(来自 txt 文件),我正在尝试对我的代码应用一些验证以产生错误因为复选框是一个变量<input type='checkbox' name='$partno'>
,所以很难设置一些验证,任何如何实现它的想法都将不胜感激。
<script>
function validateName()
{
var x=document.forms["purchase"]["visitor"].value;
if (x==null || x=="")
{
alert("Visitor name must be entered");
return false;
}
}
</script>
</head>
<body>
<h1>Items Available</h1>
<form name="purchase" action="confirm.php" method="post" onsubmit="return validateName()">
<table>
<h3>Visitor Name: <input type='text' name='visitor'></h3>
<tr><th></th><th></th><th></th><th>Price</th><th>✔</th><th>QTY</th></tr>
<?php
if (!($data = file('items.txt'))) {
echo 'ERROR: Failed to open file! </body></html>';
exit;
}
foreach ($data as $thedata) {
list($partno, $name, $description, $price, $image) = explode('|', $thedata);
echo "<tr><td><img src='$image' width='60' height='60' alt='image'></td><td><h3>$name</h3></td><td> $description</td>
<td> <b>£$price</b></td><td><input type='checkbox' name='$partno'></td><td><input type='text' size='1' name='qty' value='1'</td></tr>";
}
?>
</table>
到目前为止,我已经尝试...
function validateName()
{
var x=document.forms["purchase"]["$partno"].value;
if (x==null || x=="")
{
alert("Select atleast one item");
return false;
失败得很惨。
新代码
<script>
function validateName()
{
var x=document.getElementById("purchase").value
if (x==null || x=="")
{
alert("Visitor name must be entered");
return false;
}
}
</script>
</head>
<body>
<h1>Items Available</h1>
<form id="purchase" name="purchase" action="confirm.php" method="post" onsubmit="return validateName()">
<table>
<h3>Visitor Name: <input type='text' name='visitor'></h3>
<tr><th></th><th></th><th></th><th>Price</th><th>✔</th><th>QTY</th></tr>
<?php
if (!($data = file('items.txt'))) {
echo 'ERROR: Failed to open file! </body></html>';
exit;
}
foreach ($data as $thedata) {
list($partno, $name, $description, $price, $image) = explode('|', $thedata);
echo "<tr><td><img src='$image' width='60' height='60' alt='image'></td><td><h3>$name</h3></td><td> $description</td>
<td> <b>£$price</b></td><td><input type='checkbox' name='$partno'></td><td><input type='text' size='1' name='qty' value='1'</td></tr>";
}
?>
</table>