获取HTML5验证以使用onclick? [英] Get HTML5 validation to work with onclick?

查看:145
本文介绍了获取HTML5验证以使用onclick?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名称,公司名称,电子邮件地址和电话号码的表单,并且使用所需的格式可以确保表单中的每个输入都填充了一些内容。我试图做的是将文件下载到填写表单的访问者的计算机上,并使用此代码处理下载:

HTML:

 < input type =submitid =submitbuttononclick =download()> 

JS:

  function download(){
window.open('the_file.zip');
}

但是,添加onclick会导致表单绕过验证,并且会提交并且无需填写即可下载。我可以在这里做什么来确保HTML5验证有效?

解决方案

我会倾听提交而不是点击事件。



使用jQuery:

$ p $ $('form')。submit (function(event){
alert('form was submitted!');
// window.open('the_file.zip');
// event.preventDefault();

// ...做别的...

// $(this).submit();
});

然后,您还可以阻止提交 event.preventDefault()的默认操作; 之前,如果你想在你实际提交表单之前做一些事情。


I have a form for name, company, email, and phone number, and using required it makes sure that the form has something filled in for each input. What I am trying to do is have it download a file to the computer of the visitors who fill out the form, and have this code handling the download:

HTML:

<input type="submit" id="submitbutton" onclick="download()">  

JS:

function download(){
    window.open('the_file.zip');
}

However, adding the onclick is causing the form to bypass validation and it will submit and download with nothing needing to be filled out. What can I do here to make sure the HTML5 validation works?

解决方案

I would listen for the submit rather than the click event.

Using jQuery:

$('form').submit(function(event){
    alert('form was submitted!');
    // window.open('the_file.zip');
    // event.preventDefault();

    // ... do something else ...

    // $(this).submit();
});

Then you could also prevent the default action of submit event.preventDefault(); before if you wanted to do something before you actually submitted the form.

这篇关于获取HTML5验证以使用onclick?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆