Issue
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?
Solution
$("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.
Answered By - Chetan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.