检查以确保所有字段都已填写 [英] Check to make sure all fields are filled Jquery

查看:133
本文介绍了检查以确保所有字段都已填写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在jquery中为我的输入字段创建一个简单的验证器. 目前,我得到以下信息:

I'm trying to make an easy validator in jquery for my input fields. Currently i got the following:

function checkInputs(){
var isValid = true;
$('.input-required').each(function() {
     if($(this).val() === ''){
        isValid = false;
         return false;
     }        
 });
return isValid;
}

然后我得到一个正确的按钮:

And then i got a button right that is this:

$('#confirm').click(function () { 
    alert(checkInputs());
});

但是,即使输入为空,也总是返回true. 同样,在完成所有输入之后,将启用一个按钮来单击.

But this always returns true even if the input is empty. Also after this works am going to make to where if all inputs are filled in, a button will be enabled to click on.

对其进行了编辑,因此它现在具有选择器,仍然始终为真.

edited it so it has a selector now, still getting always true.

预先感谢

推荐答案

尝试使用filter属性获取具有required属性的输入.

Try use the filter attribute to get the inputs that has a required attribute.

$('input').filter('[required]')

添加了代码以检查输入是否已填充并启用或禁用button.请注意,如果使用此按钮,则$('#confirm').click(function());功能还有很多地方,因为仅当输入被填充时才会启用此按钮.

Added code to check if inputs are filled and enable or disable button. Note if we use this, there aint much point of the $('#confirm').click(function()); function since this button will only be enabled when the inputs are filled.

function checkInputs() {
  var isValid = true;
  $('input').filter('[required]').each(function() {
    if ($(this).val() === '') {
      $('#confirm').prop('disabled', true)
      isValid = false;
      return false;
    }
  });
  if(isValid) {$('#confirm').prop('disabled', false)}
  return isValid;
}

$('#confirm').click(function() {
  alert(checkInputs());
});

//Enable or disable button based on if inputs are filled or not
$('input').filter('[required]').on('keyup',function() {
checkInputs()
})

checkInputs()

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input required>
  <input required>
  <input required>
  <button id="confirm">check</button>
</form>

这篇关于检查以确保所有字段都已填写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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