Jquery .value returning undefined in function to return input value

Viewed 163

I know this is going to be really basic, as I can appreciate how simple this should be - but I've got myself all twisted up.

I'm just trying to make a searchbar function. This is the input -

<input class="form-control me-2 header__searchbar comic__search" type="search" placeholder="Search" aria-label="Search" style="width: 15rem; margin-left: 2rem;">

This is the code (so far), but I cant get it to return the value.

var searchbar = $(".comic__search");
var searchBarVal = ""

$("body").on("keyup", searchbar, function() {
  searchBarVal = searchbar.value;
  console.log(searchbar.value);
})

Thanks all

3 Answers

There's two separate issues here.

Firstly you cannot add a delegated event handler by providing a jQuery object in the second argument of on(), so the event is not being bound correctly (it will work for the .comic__search elements that are in the DOM when the event is bound, but not ones dynamically created at a later time, which is the point of a delegated handler). Change searchbar to a string instead.

Secondly jQuery's method is val(), not value.

var searchBarVal = "";

$("body").on("keyup", '.comic__search', function() {
  searchBarVal = $(this).val();
})

$('button').on('click', () => console.log(searchBarVal));
input {
  width: 15rem;
  margin-left: 2rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="form-control me-2 header__searchbar comic__search" type="search" placeholder="Search" aria-label="Search" />

<button>Check value</button>

Finally, note that you're not 'returning' anything here, you're just updating the variable in the higher scope.

Just replace .value to .val() because searchbar is a jQuery object.

var searchbar = $(".comic__search");
var searchBarVal = "";

$("body").on("keyup", searchbar, function() {
  searchBarVal = searchbar.val();
  console.log(searchbar.val());
});

in your example, searchbar is a jquery object and to access the value of a html input element within jquery object, you have to call the function val():

var searchbar = $(".comic__search");
var searchBarVal = "";

$("body").on("keyup", function() {
  searchBarVal = searchbar.val();
  console.log(searchbar.val());
})

or access the html elment directly through the jquery wrapper:

var searchbar = $(".comic__search");
var searchBarVal = "";

$("body").on("keyup", function() {
  searchBarVal = searchbar.get(0).value;
  console.log(searchbar.get(0).value);
})

optionally, you can also access the object directly without any jquery:

var searchbar = document.querySelector(".comic__search");
var searchBarVal = "";

btn.addEventListener('keyup', function() {
  searchBarVal = searchbar.value;
  console.log(searchbar.value);
})
Related