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?
=>functions are not like traditional functions in at least one way that makes a huge difference with jQuery code.$('#first_name')seems to indicate you may have duplicates in your "list" perhaps; and yourname.parent()feels like it might be better written - this is really outside the question scope but we may be able to give you perhaps a better event handler here given your "list" statement'input'and not'change'?