Javascript-在所有输入均有效时启用“提交"按钮 [英] Javascript - Enable Submit button when all input is valid

查看:72
本文介绍了Javascript-在所有输入均有效时启用“提交"按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个带有一些输入(名字和姓氏,用户名,生日,密码和电子邮件)的表单,并带有一些验证条件,例如:

So I have a form with some inputs (First and last name, user name, birthday, password and email) with some validation conditions which I made like this for example :

function checkfnlname(field) {
curr = document.getElementById(field).value;
if ( curr.length > 0) {
    updateCSSClass(field, 1);
    return true;
}
else {
    updateCSSClass(field, 0);
    return false;
}}

这将更改其颜色并返回true.我使用 onKeyUp =" 调用这些函数.现在,我要做的是禁用提交"按钮,直到所有字段均已完成并通过此处的功能进行了验证.我写了这个函数:

This changes it's color and return true . I call these function using onKeyUp="". Now what I want to do is make the Submit button disabled until all the fields have been completed and validated by the functions up there. I wrote this function :

function formvalid() {
if (checkfnlname('fname') && && (all other fields)) {
    document.getElementByID("submitinput").disabled = false;
}
else {
    document.getElementByID("submitinput").disabled = true;
}
return 1;}

但是我不知道怎么称呼它.(我尝试了很多发现的事情,但无济于事)这是正确的方法吗?如果可以,我该如何调用此函数?

But I have no idea how/where to call it. (I tried a lot of things I found but nothing worked) Is this the right way to do it ? if so how can I call this function ?

推荐答案

这是纯ES6和HTML5方式.

Here's a pure ES6 and HTML5 way.

您可以查看表单中的更改,然后检查表单是否有效.

You can watch your form for changes and then check to see if the form is valid.

const form = document.getElementById('form');
form.addEventListener("change", () => {
    document.getElementById('submitBtn').disabled = !form.checkValidity()
});

我已将示例从 MDN 修改为在操作中显示此内容-> https://jsfiddle.net/denov/hxf3knob/2/

I have modified an example from MDN to show this in action -> https://jsfiddle.net/denov/hxf3knob/2/

这篇关于Javascript-在所有输入均有效时启用“提交"按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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