0

I created a slider and a label to show its value:

<div style="display:table-cell; outline:5px dotted green; width:100%;"><input type="range" min="1" max="100" value="50" class="slider" id="SelectDate"></div>
<div id="visDate" style="display:table-cell; outline:5px dotted green; vertical-align:middle;"></div>

When I write the script to automatically update the label with the value, this works:

var slider = document.getElementById("SelectDate");

(meaning that I can use .value to get the value), but this doesn't:

var slider = $("#SelectDate");

When I output slider to the console, I see the object, and can see the value property in there, but can't figure out how to access it.

So, it looks like the two methods above return the slider object differently. What does each return, and what are the advantages and disadvantages of each way to find the object?

DeltaG
  • 760
  • 2
  • 9
  • 28
  • jQuery does not have `.value`.... so is this an issue of using jQuery wrong? – epascarello Feb 13 '19 at 14:15
  • $("#SelectDate") will return a JQuery object which means you can execute JQuery functions against it, like .val() to get the value, while document.getElementById("SelectDate") returns the element from the DOM. – Doug F Feb 13 '19 at 14:16
  • 1
    `var slider = $("#SelectDate")[0].value;` or `var slider = $("#SelectDate").val();` – madalinivascu Feb 13 '19 at 14:16

2 Answers2

4

The jQuery Object: The Wrapped Set: Selectors return a jQuery object known as the "wrapped set," which is an array-like structure that contains all the selected DOM elements. You can iterate over the wrapped set like an array or access individual elements via the indexer ($(sel)[0] for example). More importantly, you can also apply jQuery functions against all the selected elements.

// Vanilla JS
var slider = document.getElementById('SelectDate');
var val = slider.value;

// jQuery
var $slider = $('#SelectDate');
var $val = $slider.val();
var val = $slider[0].value; // Vanilla JS (using jQuery object)
max
  • 8,632
  • 3
  • 21
  • 55
2

jQuery returns a jQuery object. You need to access the correct index to get the value like :

$("#SelectDate")[0].value

or use .val() method

$("#SelectDate").val()
R3tep
  • 12,512
  • 10
  • 48
  • 75
  • 1
    "jQuery return an array" — No, it doesn't. (Arrays don't have a `val()` method for a start!) – Quentin Feb 13 '19 at 14:18