0

For my javascript code I tried the 2 alternative solutions in Get the value in an input text box, answer 2 from RJD22, pls see code below. Option A works fine, but option B doesnt; the console shows 'undefined' when I enter a figure (or even some text).

Any idea why B does not work? I could use option A but I want to validate that the form field has been filled in, and from the val() description (http://api.jquery.com/val/) I cannot see what val() returns when no value has been filled in.

Thnx for any comments in advance.

html code:

</label> <input id="usage" type="text" name="usage">

javascript code:

this.usage = $("#usage").val(); //OPTION A:  WORKS

this.usage = $("#usage").attr("value"); //OPTION B: DOESNT WORK

console.log(this.usage);
Community
  • 1
  • 1
Joppo
  • 715
  • 2
  • 12
  • 31

3 Answers3

2

val() returns '' (empty string) when no value has been entered. You should use val() instead of prop or attr.

Fiddle.

Icarus
  • 63,293
  • 14
  • 100
  • 115
0

attr is used to get the actual attribute from the HTML. I think you should use prop.

You can read about the difference between attr and prop here: .prop() vs .attr()

Community
  • 1
  • 1
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
0

You can use the following ways:

var currentValue = $('#usage').prop("value");

or

var currentValue =$('#usage').val();

In attr('value') you're specifically saying you're looking for the value of an attribute named value. It is preferable to use val() as this is jQuery's out of the box feature for extracting the value out of form elements.

Aditya
  • 4,453
  • 3
  • 28
  • 39