首页 > 解决方案 > 获取所有必需的输入并在页面加载时检查它们

问题描述

function showloading()
{
    $('input[required="required"]').each(function(){
        if( $(this).val() == "" ){
          alert('Please fill all the fields');
            return false;
        }
    });
    window.scrollTo(0,0);
    var x = Math.floor((Math.random() * 10) + 1);
    $("#loading-"+x).show(1000);
}

我有上面的功能现在一切正常,除了线

return false;

不只是警报工作但它继续代码我想要的是检查页面是否有必填字段它必填字段为空不要运行此代码

window.scrollTo(0,0);
var x = Math.floor((Math.random() * 10) + 1);
$("#loading-"+x).show(1000);

谢谢

标签: javascriptjquery

解决方案


这是纯javascript中的实现

function showloading() {
  // get a NodeList of all required inputs, and destructure it into an array
  const required = [...document.querySelectorAll('input[required]')];
  // Use Array.prototype.some() to find if any of those inputs is emtpy
  // and if so, return false (exiting showLoading)
  if (required.some(input => input.value === '')) {
     alert('Please fill all the fields');
     return false;
  }
  /* whatever you want to do if all required fields are non-empty */
}

推荐阅读