我制作了一个表格,要求提供姓名和电子邮件以便下载文件。问题是,无论你是否填写了名称,"下载"按钮都会起作用,尽管它会显示一条消息,告知下载文件的信息丢失。
我没有足够的js知识,无法找到在输入姓名和电子邮件时让"下载"按钮工作的方法。
有人能帮忙吗?请
HTML下载按钮:
<button type="submit" onclick="window.location.href='download/CV.pdf'">Download</button>
JS:
var email = document.getElementById("email").value;
var error_message = document.getElementById("error_message");
error_message.style.padding = "10px";
var text;
if(name.length < 5){
text = "Please Enter valid Name";
error_message.innerHTML = text;
return false;
}
if(email.indexOf("@") == -1 || email.length < 6){
text = "Please Enter valid Email";
error_message.innerHTML = text;
return false;
}
alert("Thank you!");
return true;
}
谢谢!
您可以这样做。
<form onsubmit="return validateForm(event)">
<button type="submit">Download</button>
<input type="text" id="email" placeholder="Email">
<input type="text" id="name" placeholder="Name">
</form>
...
function validateForm(event) {
event.preventDefault();
var email = document.getElementById("email").value;
var name = document.getElementById("name").value;
var error_message = document.getElementById("error_message");
error_message.style.padding = "10px";
var text;
if(name.length < 5){
text = "Please Enter valid Name";
error_message.innerHTML = text;
return;
}
if(email.indexOf("@") == -1 || email.length < 6){
text = "Please Enter valid Email";
error_message.innerHTML = text;
return;
}
window.location.href = "download/CV.pdf";
}