Getting input value with jQuery

Asked

Viewed 48,474 times

0

I’m not getting the entered value in an input field with jQuery:

HTML:

<input type="text" id="vendaMediaMensal" name="vendaMediaMensal">

jQuery:

var vendaMediaMensal = $("#vendaMediaMensal").val();

$("#vendaMediaMensal").focusout( function(){
    alert(vendaMediaMensal);
});

3 answers

8


The problem is that you are picking up the value before it exists. Leave to pick up the .val() only in the focusout:

var vendaMediaMensal = $("#vendaMediaMensal");
vendaMediaMensal.focusout( function(){
    alert(vendaMediaMensal.val());
});
  • It’s true, I’d forgotten that detail. And the value I enter in the field, I will have to convert to currency if I want to calculate with other values or no need?

  • Well, there is no currency as a type in Javascript. In your case you will probably use a parseFloat(valor).

2

Place the var inside the function:

$("#vendaMediaMensal").focusout(function(){
        var vendaMediaMensal = $("#vendaMediaMensal").val();
        alert(vendaMediaMensal);
    });

1

Just as improvement recommend using the:

 $(this).val();

So you promote the reusability of this event.

Hugs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.