0

Copy pasting the example from bootstrap's web page regarding navigation and search bars:

function thisFunction() {
  console.log($("#123").value);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form-inline my-2 my-lg-0">
  <input class="form-control mr-sm-2" id="123" type="search" placeholder="Search" aria-label="Search">
  <button type="button" class="btn btn-outline-dark" id="456" onclick="thisFunction()">Search</button>
</form>

Why does this give me an undefined? Whereas if I add [0] it then prints the value?

console.log($("#123")[0].value);

What first element does it fetch this way?

Nick
  • 138,499
  • 22
  • 57
  • 95
hazyred
  • 3,618
  • 3
  • 12
  • 14
  • 2
    What page did you see this on? It should be `($("#123").val()`. `$("#123")[0].value` dereferences the jQuery object and returns the underlying node, hence the native `value` works. – j08691 Sep 03 '19 at 02:19
  • Duplicate of [Get the value in an input text box](https://stackoverflow.com/questions/4088467/get-the-value-in-an-input-text-box) – Herohtar Sep 03 '19 at 02:23

2 Answers2

2

jQuery selectors return an object containing all elements that match the selector (try console.log($("#123")); to see this), so to use .value you need to first pick the element out of the array that you want to apply .value to. Alternatively, you can use .val() which will

Get the current value of the first element in the set of matched elements.

function thisFunction() {
  console.log($("#123").value);
  console.log($("#123")[0].value);
  console.log($("#123").val());
  console.log($("#123"));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form-inline my-2 my-lg-0">
  <input class="form-control mr-sm-2" id="123" type="search" placeholder="Search" aria-label="Search">
  <button type="button" class="btn btn-outline-dark" id="456" onclick="thisFunction()">Search</button>
</form>
Nick
  • 138,499
  • 22
  • 57
  • 95
0

When [0] is added after a JQuery object, this is giving you direct access to the first real DOM element that this JQuery object represents (or wraps). In the case of your code, you can break it down as follows:

/* A JQuery object that reprsents or "wraps" #123 */
const inputJQueryObject = $("#123");

/* Accessing the first true/real DOM element the JQuery object represents */
const inputDOMElement = inputJQueryObject[0];

/* Accessing the current value of the DOM element */
const inputDOMElementValue = inputDOMElement.value;

console.log(inputDOMElementValue);

Alternatively, you could use JQueries .val() method to access the current value of #123, avoiding the need for [0].value by doing this:

console.log( $("#123").val() );

Hope that helps!

Dacre Denny
  • 29,664
  • 5
  • 45
  • 65