I’ve been trying to figure this problem out for the last 2 days and have not found any solution so far.
Im trying to attach a .click() listener to all elements of a list, but any time I use this or $(this) none of the jquery functions work, for example using .val() returns undefined even though it has a value.
I’m using fomantic-ui but I’ve also tried the same code without and it doesn’t work either. I’m also using NodeJS and Express, in case that makes a difference.
Further testing showed me that for some reason this doesn’t work:
$('#first_name').on('input', () => {
const name = $(this)
const field = name.parent()
if (!name.val().match(/^\p{L}{1,16}$/u)) {
field.attr('class', 'field error')
name.prop('valid', false)
} else {
field.attr('class', 'field success')
name.prop('valid', true)
}
})
But if I change it to this, everything is fine:
$('#first_name').on('input', () => {
const name = $('#first_name') //Only Change...
const field = name.parent()
if (!name.val().match(/^\p{L}{1,16}$/u)) {
field.attr('class', 'field error')
name.prop('valid', false)
} else {
field.attr('class', 'field success')
name.prop('valid', true)
}
})
And also this both return false
console.log($(this) === $('#first_name'), $(this) == $('#first_name'))
//false false
I have tried all sorts of combinations but nothing I can think of works, and nothing I found anywhere online has either. Maybe I just don’t understand how this is supposed to work but I’ve tried reading the jquery documentation but it didn’t help me.
Can anyone help me?
>Solution :
You’re using an arrow function, so the value of this will be inherited from the parent context. A console.log should show you what that is.
You probably want to use a regular anonymous function, assuming jQuery calls the function with the HTML element set to the context of this.
$('#first_name').on('input', function() {
// ...
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Arrow functions don’t have their own bindings to this or super, and
should not be used as methods.