1

Trying to implement 'required' attribute on IE<11 and Safari.

Here is the script I am using to try to accomplish this, but it isn't working. Looking for feedback or a slap in the face if necessary. The form id = "sendit"

$("#sendit").submit(function() {
 if (!attributeSupported("required") || ($.browser.safari)) {
  $("#sendit [required]").each(function(index) {
   if (!$(this).val()) {
    alert("Please fill all required fields.");
    return false;
    }
  });
 }
}); 
Claire
  • 3,146
  • 6
  • 22
  • 37
  • Try $("#sendit [required=required]") instead – Joshua G Aug 14 '15 at 02:52
  • What old version of jQuery are you using that $.browser works? – epascarello Aug 14 '15 at 02:57
  • Try $("#sendit input[required=required]") maybe, the attr selector is sometimes a bit particular – Joshua G Aug 14 '15 at 02:57
  • You should be checking for support like this: http://stackoverflow.com/questions/8550642/check-if-a-browser-has-built-in-html5-form-validation not with sniffing browsers. Did you debug the code to see what is failing? console.log() is your friend. – epascarello Aug 14 '15 at 02:59
  • @epascarello the console says I am missing a `)` after the argument list, but I do not see that. Thank you for pointing out that this is old code. I removed $.browser `if` statement and replaced it with a `!` version of the `if` statement from your link – Claire Aug 14 '15 at 03:11
  • And what line does it point too for the missing )? My guess it is not this code – epascarello Aug 14 '15 at 03:16

1 Answers1

1

This is an old post, but I see it wasn't answered. The problem with your code is that you have the "return false" within the "each" function. That breaks out of the each loop but doesn't stop the form submit. I would just remove the browser checks since any browser that supports html5 form validation will pass the test. So you should be able to change the code to this:

$("#sendit").submit(function() {
  var valid = true;
  $("#sendit [required]").each(function(index) {
    if (!$(this).val()) {
      alert("Please fill all required fields.");
      valid = false
      $(this).focus();
      return false;
    }
  });
  if (!valid) {
    return false;
  }
  
  // anything else that need to be done on submit
});

Note that I added a line to focus the form field as well.

David Hammond
  • 3,286
  • 1
  • 24
  • 18