1

In a view, I'm trying to retrieve the value of an html input box AFTER I have changed it. In other words, the page loads with

<input id="input_one" type="text" value = "apple" />

When the page opens the input box has the word apple in it. I click on this input box, erase the word apple, and then write the word "orange" in instead. when I do the following:

$('#input_one').click(function() {
    console.log($('#input_one').attr('value'));
});

the result is "apple" not orange. Is there a way to get the new value I just input without submitting the form? I'm trying to make client side validation using javascript on the page, if the value is something, submit form, otherwise display message "value must be something"

maybe I can do something like

 $('#input_one').attr('value', 'new value'); 

but how do I get the new value I just put in? where is this new value stored? innerHTML? or text() maybe?

Abdul Ahmad
  • 9,673
  • 16
  • 64
  • 127

3 Answers3

3

attr() will get the attribute of the <input>, which is the initial value of the element.

The current value of the element is a property. If we wanted to get any element property:

$('#input_one')[0].value;    
$('#input_one').prop('value');

However, jQuery has the perfect method, .val(), for you:

$('#input_one').val();

What is the difference between attribute and property?

Community
  • 1
  • 1
George
  • 36,413
  • 9
  • 66
  • 103
1

Try .val() instead:

$('#input_one').val();
Salil Dabholkar
  • 622
  • 3
  • 7
0

Try something like this:

$("#input_one").blur(function() {
   alert(this.value); 
});

This alerts the new value of the input box every time you put it out of focus.

boxsome
  • 178
  • 5