Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the jquery object not returning its value?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading