Awar Pulldozer
Awar Pulldozer

Reputation: 1101

get all required inputs and check them on page load

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);
}

i have the above function now everything working fine except that the line

return false;

didn't work just the alert working but its Continuing the code what i want is to check if the page has required field it the required field is empty dont run this code

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

thanks

Upvotes: 0

Views: 47

Answers (1)

connexo
connexo

Reputation: 56773

Here is an implementation in pure 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 */
}

Upvotes: 1

Related Questions