Javascript禁用按钮,直到填写所有字段 [英] Javascript disable button until all fields are filled

查看:77
本文介绍了Javascript禁用按钮,直到填写所有字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

会很感激帮助解决这个问题。
需要使事件侦听器适用于所有元素。所以基本上当你填写名字,姓氏,即所有字段时,只有按钮应该被启用,即使其中一个字段为空,按钮也应该被禁用。

would appreciate some help solving this. Need to make the event listener work for all the element. So basically when you fill out name, last-name i.e all the fields then only the button should get enabled, Even if one of the fields is empty the button should get disabled.

 (function () {
 "use strict";

 var knapp = document.getElementById('skicka');

 knapp.disabled = true;

 var f=document.getElementById('fornamn');
 var e=document.getElementById('efternamn');
 var p=document.getElementById('passnr');
 var n=document.getElementById('nat');

 e.addEventListener('change',function(){

  if(e.value==='' ){

 knapp.disabled=true;
   }

 else{
  knapp.disabled=false;
 }
  });

  })();


推荐答案

let inputs = document.querySelectorAll('[type="text"]'),
    knapp = document.querySelector('#skicka')
knapp.disabled = true

for (i = 0; i < inputs.length; i++) {
  inputs[i].addEventListener('input',() => {
    let values = []
    inputs.forEach(v => values.push(v.value))
    knapp.disabled = values.includes('')
  })
}

<form>
  <input id=fornamn type=text><br>
  <input id=efternamn type=text><br>
  <input id=passnr type=text><br>
  <input id=nat type=text><br>
  <input type=button id=skicka value=Complete>
</form>

这样做。我更喜欢输入上的eventhandler而不是更改,这样您就可以在键入时看到按钮被启用。每次在任何字段中输入任何内容时,它将立即获取所有值并将它们添加到数组中。从$ ES6开始, .includes()是一种检查数组特定值并返回布尔值的方法。

This will do it. I prefer the eventhandler on input not change, so that you can see the button being enabled as you type. Every time you enter anything in any of the fields it will get all values at once and add them to an array. The .includes(), new as of ES6, is a method that checks for a specific value of an array and returns a boolean.

这篇关于Javascript禁用按钮,直到填写所有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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