Javascript:根据单选按钮选择重定向到新页面



如果单击"是"按钮,我正在尝试做的是重定向到新页面。如果他们单击"否",我已经设置了提示。但是,需要填写一个表单(姓名和电子邮件)才能正常工作。 如果他们不填写这些详细信息,我希望出现一个提示,告诉用户他们需要填写它们才能继续。

我对javascript相当陌生,所以任何提示或解释将不胜感激。

下面是 html 代码

<input type="radio" name="radio" id="yes"><strong>Yes, I agree.</strong> 
<br>
<input type="radio" name="radio" id="no" checked="checked"><strong>No, I do not agree.            </strong><br>
<br>    
If you agree, please enter your full name and email address in the spaces below and press   submit.
<br>
<form> Full Name:<input type="text" name="fullname"></form>
<br>  
<form> Email Address:<input type="text" name="email"></form>
<br>     
<br>
<form action="endPage.jsp" id="form">
<input type="submit" id="submit" value="Submit" name="submit" />
</form>

还有JavaScript代码

var submitBtn = document.getElementById("submit");
var termsChk = document.getElementById("yes");
var formFrm = document.getElementById("emailField");
var formFrm = document.getElementById("nameField");
submitBtn.addEventListener("click", function() {
if (termsChk.checked === true && formFrm)
{
    alert("Checked!");
    formFrm.submit();
} else {
    alert("Please Contact Spearhead Mining Corporation: projects@spearheadmining.com to discuss your options for project submittal!");
}
return false;
});

将 window.confirm() 与发送给用户的 spcific 消息一起使用,并使用 window.location() 重定向到新的 URL。

result = window.confirm("Message to user");
if(result) {
     window.location = "new url";
} else {
     //do the rest of logic
}

对于更具体的答案,如果您发布是和否按钮的代码以及表单的 HTML 代码,可能会有所帮助。话虽如此,您通常处理此问题的方式是在 yes 按钮的代码中,您可以运行您需要运行的任何客户端验证,在这种情况下检查名称和电子邮件字段是否不为空,然后显示您的错误消息而不是重定向如果一切都无效。

例如,在您的 yes 处理程序中

if(document.getElementById('emailField').value == null || document.getElementById('namefield') == null){
  /*error handling code goes here*/
  return
 }
else{
  /*redirection code goes here*/
}

最新更新