David Li David Li - 11 months ago 53
Javascript Question

HTML5/JavaScript/jQuery - Input Range .value() becomes undefined when using jQuery selector?

So I'm trying to make a input range object to allow the user to select from a range of values, and reading this and updating a jQuery variable.

If I try to access the value of:

<input id="scroll" type="range" min="1" max="60" value="5">

If I use:

$("#scroll").on("change", function() {
variable = this.value;

it functions correct and the variable updates.

However, if I use the jQuery tag selector, as follows:

$("#scroll").on("change", function() {
variable= $("#scroll").value;

variable becomes undefined.

Could you explain why? My thought is that "this" is referring to the HTML object as it is updated, and uses the HTML attribute, but frankly I don't know enough about it.

Answer Source

The correct syntax is $("#scroll").val(). You left out the # and you used the DOM property instead of the jQuery method.

$("#scroll").on("change", function() {
    variable= $("#scroll").val();