0

Can the javascript below to individually have different custom validity depending on what information is actually being entered in the field. eg. For Name: "please enter a name". For Location: "please enter a location. The loop part in the script is confusing me a little!

HTML

<form id="sidebarform" onsubmit="return false" method="post" name="myForm" >
   <input type="text" name="name" id="username" placeholder="Name (eg. Rob James)"required><br>
   <input type="text" name="location" id="userlocation" placeholder="Location (eg. Wacol)" required><br>
   <input type="submit" id="sidebarformsubmit" value="Submit">
</form> 

JAVASCRIPT

<script >
$(document).ready(function() {
    var elements = document.getElementsByTagName("INPUT");
     for (var i = 0; i < elements.length; i++) {
       elements[i].oninvalid = function(e) {
         e.target.setCustomValidity("");
        if (!e.target.validity.valid) {
            e.target.setCustomValidity("Please enter a name.");

        }
    };
    elements[i].oninput = function(e) {
        e.target.setCustomValidity("");
    };
  }
 })
 </script>

I was following this question for the initial custom validity.

HTML5 form required attribute. Set custom validation message?

Community
  • 1
  • 1
homer5677
  • 585
  • 1
  • 6
  • 11

1 Answers1

1

How about using a selector other than just getting everything by tagName, and then set whatever validity you want

$(document).ready(function () {
    $('#username').on({
        invalid: function (e) {
            e.target.setCustomValidity("");
            if (!e.target.validity.valid) {
                e.target.setCustomValidity("Please enter a name.");
             }
        },
        input: function(e) {
            e.target.setCustomValidity("");
        }
    });

    $('#userlocation').on({
        invalid: function (e) {
            e.target.setCustomValidity("");
            if (!e.target.validity.valid) {
                e.target.setCustomValidity("Please enter a location.");
             }
        },
        input: function(e) {
            e.target.setCustomValidity("");
        }
    });
});

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388