Reputation: 3841
What I am wanting to achieve is having multiple search forms throught my website without having to call a seperate selector
for each one. I've tried messing around with this
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?
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;
}
})
Upvotes: 4
Views: 389
Reputation: 35491
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();
Upvotes: 3
Reputation: 10909
Based off my comment, here is an example using some of your code:
$('.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>
Upvotes: 1