I have an input with the albaran class and I want to trigger this event when I enter the input, but I have not succeeded.
$('.albaran').on('focus', function () {
console.log($(this).data('error'));
});
I have an input with the albaran class and I want to trigger this event when I enter the input, but I have not succeeded.
$('.albaran').on('focus', function () {
console.log($(this).data('error'));
});
Since your element is created dynamically, the listener of the event must be implemented throughout the document, so that as a parameter, it is the class of your element:
$input = $("<input class='albaran' type='text' data-error='Error'/>");
$('body').append($input);
$(document).on('focus', '.albaran', function () {
console.log($(this).data('error'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
It should work.
Here is the working example:
$(function(){
$('.albaran').on('focus', function() {
console.log($(this).data('error'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="albaran" data-error="mensaje de error">
Here's another example.
var input = document.querySelector('input'),
log = document.querySelector('.log');
multipleEventsListeners(input, 'keyup change', function(e){
log.textContent = 'Valor agregado: ' + this.value;
});
function multipleEventsListeners(elem, events, func) {
var event = events.split(' ');
for (var i = 0; i < event.length; i++) {
elem.addEventListener(event[i], func, false);
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<input type="number" value="1" />
<p class="log"></p>
</body>
</html>
If the element is not dynamically created, I recommend using the function .focus()
In simple terms your code would be:
$('.albaran').focus(function () {
console.log($(this).data('error'));
});
If you have any questions, comment.
Luck.
Update
In that case the only thing you should do is change the single quotes for doubles, I know it sounds silly, but I had a similar problem but with "click"
$('.albaran').on("focus", function () {
console.log($(this).data('error'));
});
If you have a question, please comment, Luck.
you must change your code for the following
$('.albaran').on('focusin', function () {
console.log($(this).data('error'));
});
......
The JQuery focusin event method is presented only when the input or element of the DOM is focussed and, as a result of that event, generate a reaction.
You can know more about it from the following link. link which is the official JQuery site