skip to Main Content

This question has probably been asked and answerd a thousand times before, but I don’t know if it’s because of SEO, I’ve not found a suitable solution. I either get undefined or blank text in Chrome.

$('input[type="text"]').on('input', (a, b) => {
    console.log(this.value);
});

This keeps returning undefined in the console I’ve also tried:

$('input[type="text"]').on('input', (a, b) => {
       console.log(b);
    });

$('input[type="text"]').on('input', (a, b) => {
       console.log($(this).val());
    });

$('input[type="text"]').on('input', (a, b) => {
       console.log(a.value);
    });

$('input[type="text"]').on('input', (a, b) => {
       console.log(b.value);
    });

Any idea’s would be very appreciated.

2

Answers


  1. The this keyword will not work us you expect since you’re using es6 arrow function format what will change the context, use e.target instead of it.

    Take a look at What does “this” refer to in arrow functions in ES6?

    $('input[type="text"]').on('input', (e) => {
      console.log(e.target.value);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="text" value="test">
    Login or Signup to reply.
  2. This is because you are using arrow function the scope of which is different from normal function.

    Normally you can replace arrow function with conventional function expression & use $(this) or use the target object from event handler to get the value of the input

    $('input[type="text"]').on('input', function(a, b) {
      console.log($(this).val());
    });
    
    $('input[type="text"]').on('input', (a, b) => {
      console.log(a.target.value);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type='text'>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search