Multiple search input using `this` for value

What I want to achieve is that I have several forms of search on my website without having to name a separate one selectorfor each of them. I tried messing around with thisto get the current value and use it on keydown, but anytime when I submit the search, the only value I get is this [object Object]. What am I doing wrong here?

HTML

  <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>
        <div class="checkbox">
          <label>
            <input type="checkbox">
            <span>Translate my search</span>
          </label>
        </div>
      </div>
    </div>
  </div>

Js

$('.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;
        }
    })
+4
source share
2 answers

The 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'));

    // ...

keydown SearchInput, <input>. , this <input>, keydown. , find() <input> (.. this), <input> , .

:

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

, val()

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

, :

$('.SearchInput').bind('keydown', function(e) {
  if (e.keyCode == 13) {
    var search = $(this).val();
    console.log(search);
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>
      <div class="checkbox">
        <label>
          <input type="checkbox">
          <span>Translate my search</span>
        </label>
      </div>
    </div>
  </div>
</div>
Hide result
+1

Source: https://habr.com/ru/post/1651471/


All Articles