1

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.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Ezrab_
  • 825
  • 5
  • 19
  • 44

2 Answers2

6

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">
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
3

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'>
brk
  • 48,835
  • 10
  • 56
  • 78