Jquery event when entering input? [closed]

0

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'));
});
    
asked by Acd 15.06.2017 в 00:22
source

5 answers

0

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>
    
answered by 15.06.2017 / 00:30
source
0

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">
    
answered by 15.06.2017 в 00:27
0

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>
    
answered by 15.06.2017 в 00:29
0

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.

    
answered by 15.06.2017 в 00:26
0

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

    
answered by 15.06.2017 в 00:26