即使下面的代码工作正常,我的老板提到我应该返回一个标志(变量)而不是返回true或false。我理解那部分,但我的问题是如何在表单中获取变量的值。这是我的表格:
<form id="myForm" action="post.php" method="post" onsubmit="return validate();">
这是我的JavaScript代码
function validate(){
if(document.getElementById('postTW').checked || document.getElementById('postFB').checked){
var twFlag = false;
var fbFlag = false;
var form = document.getElementById("myForm");
var twChecker = document.getElementsByName('twitter[]');
var fbChecker = document.getElementsByName('fbPages[]');
for (var i = 0; i < twChecker.length; i++) {
if(twChecker[i].checked){
twFlag = true;
}
};
for (var j = 0; j < fbChecker.length; j++) {
if(fbChecker[j].checked){
fbFlag = true;
}
};
if(twFlag === false && fbFlag === false){
alert("We can't proceed, not enough arguments");
form.reset();
return false;
}
if (fbFlag === twFlag){
alert("tw and fb would be posted");
return true;
}
else if (fbFlag === true && twFlag === false)
{
alert("only fb would be posted");
return true;
}
else if (fbFlag === false && twFlag === true){
alert("Only tw would be posted");
return true;
}
else{
alert("Not enough arguments ");
form.reset();
return false;
}
}
else{
alert("Not enough arguments to submit the form");
return false;
}
}
感谢您的任何建议
答案 0 :(得分:0)
将此作为更具体的答案添加。
在表单中,添加:
<input type="hidden" name="flagged" id="flagged" value="0">
验证函数中的:
if (fbFlag === twFlag){
alert("tw and fb would be posted");
document.getElementById("flagged").value = 1;
return true;
}
现在您已将表单标记为已提交,您可以像在PHP端的任何其他POST一样检索该表单。
答案 1 :(得分:0)
您可以像这样使用type="hidden"
的输入字段
<input type="hidden" name="myfield" value="your_value">
然后在像这样的JavaScript中使用它
function validate(){
var temp;
//code here
.....
if(twFlag === false && fbFlag === false){
alert("We can't proceed, not enough arguments");
form.reset();
temp = document.getElementById("myfield").value;
// assigned value to temp variable, assign true or false as value to temp if you are returning it before form submission
return temp; //returning temp value
}
if (fbFlag === twFlag){
alert("tw and fb would be posted");
temp = document.getElementById("myfield").value;
// assigned value to temp variable, assign true or false as value to temp if you are returning it before form submission
return temp; //returning temp value
}
.....
}
或
你可以像这样为你的函数声明一个全局变量
var flag=false;//here I've set default value as false
function validate(){
.....
//code here and use flag variable
//for eg take this part of your code
if(twFlag === false && fbFlag === false){
alert("We can't proceed, not enough arguments");
form.reset();
flag = false;// assigning value to flag variable
return flag; //returning flag
}
if (fbFlag === twFlag){
alert("tw and fb would be posted");
flag = true;// assigning value to flag variable
return flag; //returning flag
}
.....
}