NooBskie NooBskie - 2 months ago 4x
Javascript Question

Multiple Search Input's Using `this` for Value

What I am wanting to achieve is having multiple search forms throught my website without having to call a seperate

for each one. I've tried messing around with
to get the current value and use that on keydown but anytime I submit the search the only value I get is
[object Object]
. What am I doing wrong here?


<div class="col-md-8 col-md-offset-2">
<div class="form-horizontal">
<div class="form-group">
<div class="fa fa-search pull-left"></div>
<div class="col-md-9">
<input autocomplete="off" class="form-control SearchInput" name="search" placeholder="Search for your products!" value="" type="text">
<div class="checkbox">
<input type="checkbox">
<span>Translate my search</span>


$('.SearchInput').bind('keydown', function(e) {
if (e.keyCode == 13) {
url = $('base').attr('href') + 'index.php?route=product/search';
var search = $(this).find($('input[name=\'search\']').attr('value'));
if (search) {
url += '&filter_name=' + encodeURIComponent(search);
var search_directly = $("select[name='search_directly']").val();
if (search_directly == 1) {
url += '&search_directly=1';
location = url;


Your main problem is this line:

$('.SearchInput').bind('keydown', function(e) {
  if (e.keyCode == 13) {
    // ...

    // here, `this` is already your input, no need to call .find()
    var search = $(this).find($('input[name=\'search\']').attr('value'));

    // ...

You are binding the keydown listener on all elements with the class SearchInput, which are your <input> elements. This means that, within your event handler, this will refer to the current <input> on which the event keydown happened. Where you are going wrong is calling find() on your current <input> element (i.e. this) which searches for other input elements inside of it, and those do not exist.

This is how that line should look:

var search = $(this).attr('value');

Or even shorter, you can use val()

var search = $(this).val();