kaldoran
kaldoran

Reputation: 855

JQuery - .val() return old value

I've got a some trouble, i use https://github.com/mailcheck/mailcheck

with this function

                $('#email').on('keypress', function(event) {
                $(this).mailcheck({
                    suggested: function(element, suggestion) {
                        $('#email_check').html("Did you mean <b><i><a href='#' id='suggest_email'>" + suggestion.full + "</a></b></i>?");
                        $('#suggest_email').on('click', function(event) {
                            event.preventDefault();
                            $('#email').val($(this).text());
                            $('#email_check').empty();
                            $('.error_js').empty()
                        });
                    },
                    empty: function(element) {
                        $('#email_check').empty();
                        $('.error_js').empty()
                    }
                });
            });

But when the script use :

opts.email = this.val(); 

(line 263 of this file https://github.com/mailcheck/mailcheck/blob/master/src/mailcheck.js )

this.val() return the old value of my input. i've tried to use a

this.attr("value");

and

this.prop("value");

Same problem.

When i do a console.log(this); and look for the value of my input, in the object, it's good, it contain the good value.

How to get the proper value then ? That's why i request your help.

Thanks.

Upvotes: 6

Views: 3084

Answers (2)

Shomz
Shomz

Reputation: 37711

The console log object show the object properties at the time the object was first expanded, so in your case the value is not yet being set when the keypress event triggers, but when you read it later in the console, it's set. To see the actual current state of the object property, log that property only instead of the whole object.

The keyup event should work fine instead.

Upvotes: 1

AmmarCSE
AmmarCSE

Reputation: 30607

Do not use the keypress event because it is fired before the new value or character is registered in the input. Use keyup instead

$('#email').on('keyup', function(event) {
                $(this).mailcheck({
                    suggested: function(element, suggestion) {
                        $('#email_check').html("Did you mean <b><i><a href='#' id='suggest_email'>" + suggestion.full + "</a></b></i>?");
                        $('#suggest_email').on('click', function(event) {
                            event.preventDefault();
                            $('#email').val($(this).text());
                            $('#email_check').empty();
                            $('.error_js').empty()
                        });
                    },
                    empty: function(element) {
                        $('#email_check').empty();
                        $('.error_js').empty()
                    }
                });
            });

Upvotes: 10

Related Questions