2010-12-20 30 views
0

我有一个表单有多个问题,每个问题都要求选择通过,失败或不适用的单选按钮。我想要实现的是,如果用户为任何问题选择“失败”并尝试提交,则会打开3个文本字段的验证。验证输入字段,如果某个单选按钮被选中

如果用户在任何问题上选择“失败”,则必须完成所有三个文本输入字段,并且除非他们这样做才能提交。

另外我已经对问题进行了验证,以确保用户为每个字段选择单选按钮,因此解决方案必须能够像现在一样使用它。一个例子是我的形式是

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
<title>Form</title> 
<script> 
function valbutton(thisform) { 

// Question 1 
myOption = -1; 
    for (i=thisform.questionone_one.length-1; i > -1; i--) { 
     if (thisform.questionone[i].checked) { 
     myOption = i; i = -1; 
     } 
    } 
    if (myOption == -1) { 
     alert("Please select Pass, Fail or N/A for Question 1"); 
    return false; 
    } 

// Question2 
myOption = -1; 
    for (i=thisform.questiontwo.length-1; i > -1; i--) { 
     if (thisform.questiontwo[i].checked) { 
     myOption = i; i = -1; 
     } 
    } 
    if (myOption == -1) { 
     alert("Please select Pass, Fail or N/A for Question 2"); 
    return false; 
    } 

//etc... 

thisform.submit(); 
} 
</script> 
</head> 

<body> 

<form method="post" action="send.php" enctype="multipart/form-data" class="form" name="claimform" id="claimform"> 

<div>1. Question? <input type="radio" name="questionone" class="radio" value="P" /> Pass &nbsp;&nbsp;&nbsp; <input name="questionone" type="radio" class="radio" value="F" /> Fail &nbsp;&nbsp;&nbsp; <inputname="questionone" type="radio" class="radio" value="N/A" /> N/A</div> 

<div>1. Question? <input type="radio" name="questiontwo" class="radio" value="P" /> Pass &nbsp;&nbsp;&nbsp; <input name="questiontwo" type="radio" class="radio" value="F" /> Fail &nbsp;&nbsp;&nbsp; <inputname="questiontwo" type="radio" class="radio" value="N/A" /> N/A</div> 

<button type="submit" title="Submit Claim" class="button" onclick="valbutton(claimform);return false;"><span><span>Submit Claim</span></span></button> 
<button type="button" title="Reset" class="button" onclick="this.form.reset()"><span><span>Clear Form</span></span></button> 

</form> 

</body> 
</html> 

任何想法?

另外我忘了提及我在这个页面中使用Mootools,所以任何解决方案应该与Mootools 1.2一起使用。

回答

1

首先,您应该使用var关键字声明变量。否则,你会污染全局名称空间,并且JavaScript必须通过堆栈向上移动以查找变量。

现在,至于你的问题...我喜欢用jQuery。如果你喜欢使用普通的旧JavaScript,那么你可以翻译它。

function submitMyForm() { 
    var failAnswers = $('input[type=radio]').filter(function() { return $(this).val() == "F"; }); 
    if (failAnswers.length > 0) { 
    var blankTextFields = $('input[type=text]').filter(function() { return $(this).val() == ""; }); 
    if (blankTextFields.length > 0) { 
     alert('Please answer the questions'); 
     return false; 
    } 
    } 

    myForm.submit(); 
} 

这就是我们所做的。首先,我们找到所有带有“F”答案的单选按钮。如果至少有一个,我们会找到所有没有输入的文本框。如果其中至少有一个,我们弹出警报消息并返回false。否则,一切都很好,我们提交表格。