【发布时间】:2015-03-31 23:57:54
【问题描述】:
我想在选择单选按钮时显示特定的表单。 该代码似乎对我来说很好,除了当页面加载时它显示两个表单而不是一个表单,其值在输入标签中被检查
<?php
function print_form()
{
$newform = "
<body>
<section>
<div><strong>Select your Quantity Format</strong></div>
<input type=\"radio\" id=\"radio1\" name=\"radios\" value=\"radio1\" checked onclick=\"show()\">
<label for=\"radio1\">Per Unit</label>
<input type=\"radio\" id=\"radio2\" name=\"radiOS\" value=\"radio2\" onclick=\"show()\">
<label for=\"radio2\">Per Box</label>
<form method=\"post\" id=\"unit\" action=\"{$_SERVER['PHP_SELF']}\" >
<table border=1 cellpadding=3 cellspacing=3 width='30%'>
<tr>
<th colspan=2 align='left' bgcolor='#EAEAEA'>Add Medicine/Item Details</th>
</tr>
<tr>
<td>Medicine/Item Name</td>
<td><input type=\"text\" name=\"Medicine/Item_Name\"></td>
</tr>
<tr>
<td>Company Name</td>
<td><input type=\"text\" name=\"Company_Name\"></td>
</tr>
<tr>
<td>Stowage Rack No.</td>
<td><input type=\"text\" name=\"Rack\" onkeypress=\"return isNumberKey(event)\" ></td>
</tr>
<tr><td colspan=2><input type=\"submit\" value=\"Add Record\">
<input type=\"hidden\" value=\"true\" name=\"unit\"></td></tr>
</table></form>
<form method=\"post\" id=\"box\" action=\"{$_SERVER['PHP_SELF']}\" >
<table border=1 cellpadding=3 cellspacing=3 width='30%'>
<tr>
<th colspan=2 align='left' bgcolor='#EAEAEA'>Add Medicine/Item Details</th>
</tr>
<tr>
<td>Medicine/Item Name</td>
<td><input type=\"text\" name=\"Medicine/Item_Name\"></td>
</tr>
<tr>
<td>Company Name</td>
<td><input type=\"text\" name=\"Company_Name\"></td>
</tr>
<tr>
<td>Minimum Stock (Boxes)</td>
<td><input type=\"text\" name=\"Minimum_Stock_box\" onkeypress=\"return isNumberKey(event)\"></td>
</tr>
<tr>
<td>Stowage Rack No.</td>
<td><input type=\"text\" name=\"Rack\" onkeypress=\"return isNumberKey(event)\" ></td>
</tr>
<tr><td colspan=2><input type=\"submit\" value=\"Add Record\">
<input type=\"hidden\" value=\"true\" name=\"box\"></td></tr>
</table></form>
</section>
<body>
";
return $newform;
}
if(isset($_POST['unit']))
{
save_record_unit();
}
else if(isset($_POST['box']))
{
save_record_box();
}
else
{
print print_form();
}
?>
我使用的 JavaScript 如下
function show()
{
var radios = document.getElementsByName("radios");
var unit = document.getElementById("unit");
var box = document.getElementById("box");
box.style.display = 'block';
for(var i = 0; i < radios.length; i++) {
radios[i].onclick = function() {
var val = this.value;
if(val == 'radio1' ){
unit.style.display = 'block';
box.style.display = 'none';
}
else if(val == 'radio2'){
unit.style.display = 'none';
box.style.display = 'block';
}
}
}
}
【问题讨论】:
-
如果你想要一个单选按钮从服务器中提取信息,你应该使用 AJAX。如果您已经知道表单的外观取决于所选的收音机,那么您可以使用 JavaScript 完成这一切。
-
@PHPglue 我知道表单的外观,并且我正在使用 JavaScript,但问题是一旦页面加载,两个表单都会出现而不是一个。
标签: javascript php html forms radio-button