做了一些谷歌搜索后,我仍然感到困惑...... 我试图通过隐藏字段将计数的单选按钮值(Javascript)传递给PHP,稍后将插入数据库MySQL。 我有一个名为test.html的表单
<html>
<head><script type="text/javascript" src="../js/script.js"></script</head>
<body>
<form name="myform" method="post"
onSubmit="return validateRadio()" action="">
<table class="tftable" border="1">
<tr><th><div align="center" class="tftable th">Questions</div></th><th colspan="2"><div align="center">Answer</div></th>
</tr>
<tr>
<td>I like to dance</td>
<td>
<label></label>
<label>
<input name="bm1" type="radio" value="1" />
Yes</label>
</td>
<td>
<label></label>
<label>
<input name="bm1" type="radio" value="2" />
No
</label>
</td></table>
<input type="hidden" name="passvalue" id="passvalue" value="">
</form>
</body>
</html>
这是计算单选按钮的script.js ...我要传递的值是answeramount值
function validateRadio()
{
// get all the inputs type
var inputs = myform.elements;
var radios = [];
// find the radio type
for (var i = 0; i < inputs.length; ++i) {
if (inputs[i].type == 'radio') {
radios.push(inputs[i]);
}
}
var countChecked = 0;
for (var j = 0; j < radios.length; j++) {
if (radios[j].checked) {
countChecked++;
}
}
//count number of radio button with value=1
var answeramount = 0;
for (var k = 0; k < radios.length; k++){
if(radios[k].checked && radios[k].value==1){
answeramount++;
}
}
if (countChecked != radios.length / 2){
alert("All questions must be answered.");
return false; // abort submit
} else {
alert("All questions have been answered.");
return true; // proceed to submit
}
}
请告诉我如何将“answeramount”值传递给php,稍后将插入数据库。感谢
编辑:
这是jsFiddle
答案 0 :(得分:0)
您可以使用该简单代码来操纵输入的值:
var field = document.getElementById('#passvalue');
field.value = answeramount;
将此剪切放在计数和警报之间
php方面将是sql脚本的标准POST(有几个教程) 您隐藏的输入将是$ _POST [&#39; passvalue&#39;]
答案 1 :(得分:0)
更正您的HTML:阅读评论!
并在您的函数中添加
...
else {
alert("All questions have been answered.");
document.getElementById("passvalue").value = answeramount;
return true; // proceed to submit
}
...
在PHP中,您可以从 $ _ POST [&#39; passvalue&#39; ] 强>
<?php
$passvalue = ( isset( $_POST[ 'passvalue' ] ) ? (int)$_POST[ 'passvalue' ] : 0 );
?>
更新: 更易读的代码:
<?php
// check: if the index "passavlue" is set
// equivalent to ternary operator [ expression ? <give true> : <give false> ]
if( isset( $_POST[ 'passvalue' ] ) ){
// cast the string to integer
$passvalue = (int) $_POST[ 'passvalue' ];
}
else{
$passvalue = 0;
}
?>
答案 2 :(得分:0)
$ passvalue = isset($ _ POST [ 'passvalue'])$ _ POST [ 'passvalue']:? “”;
passvalue字段应该
input type =“hidden”name =“passvalue”id =“passvalue”value =“echo $ passvalue;”
并在javascript
警告(“所有问题都已得到解答。”); document.getElementsById('passvalue')。Value = answeramount;