Reputation: 985
I would like to have a form (injected via ajax) that has multiple validations. Something like this:
<div data-form> <!-- Already on the page -->
<!-- Coming from API -->
<form>
<input type="number" data-input-decimal>
<input type="number" data-input-integer>
<input type="submit">
</form>
</div>
And this is my jQuery:
var $DATA_INPUT_DECIMAL = $('[data-input-decimal]');
var $DATA_INPUT_INTEGER = $('[data-input-integer]');
var $FORM = $('[data-form]');
$FORM.on('keydown', $DATA_INPUT_DECIMAL, function(e) {
console.log('banana');
// This is the validation for the input with decimal
}
$FORM.on('keydown', $DATA_INPUT_INTEGER, function(e) {
console.log('apple');
// This is the validation for the input with ONLY NUMBERS (0-9)
}
The weird part is when I test on the browser, both of these functions are being called when I keydown
any of the input
s inside the form. How do I set up different validations properly in this situation?
Thanks in advance!
Upvotes: 1
Views: 41
Reputation: 177975
You need simple delegation:
$('[data-form]').on('keydown', 'input', function(e) {
if ($(this).is('[data-input-decimal]')) {
console.log('decimal');
} else if ($(this).is('[data-input-integer]')) {
console.log('integer');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div data-form>
<!-- Already on the page -->
<!-- Coming from API -->
<form>
<input type="number" data-input-decimal>
<input type="number" data-input-integer>
<input type="submit">
</form>
</div>
Upvotes: 1