Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html5 validation on invalid event listener not firing

I have a form in my html with following markup

<form>
    <input type="text" name="fname" required>
    <input type="submit" value="Submit">
</form>

I also have 2 script tags one for jquery and the other for my javascript which I call validate.js

<script src="jquery-2.1.4.min.js"></script>
<script src="validate.js"></script></body>

When I put the following code into my validate.js file and submit invalid data. The page alerts 'invalid' as expected.

$("form input").on("invalid", function() {
     alert("invalid");
});

When I use this code in validate.js instead, when I click on the input the page again behaves as expected this time alerting 'click'.

$("body").on("click", "form input", function(){alert("click");});

However the following code does not work. When invalid data is submitted the invalid event handler does not fire and 'invalid' is not alerted as it should be.

$("body").on("invalid", "form input", function(){alert("invalid");});

I would like to do it this way because in my application I add a form to my page from an ajax request and therefore I want to attach the event handler to the body rather than the form itself. Is there any reason why this is not working?

like image 508
Dave Barnett Avatar asked Sep 02 '15 09:09

Dave Barnett


1 Answers

$("body").on("invalid", "form input", function(){alert("invalid");}); This might not work because this is a live event, where the event is attached to body and triggers invalid for body and not for form input.

$("body").on("click", "form input", function(){alert("invalid");}); For example if we change it to click, the event listens to body click and then propagates the event to form input.

Try using the direct selector.

like image 98
Chetan Avatar answered Nov 15 '22 03:11

Chetan