I have a problem, I tried to select CLOSEST to .search_box
element with class .results
using jQuery and show list from PHP.
$(".results").show().append(html)
This works bad, because list from PHP showed near all elements. I have few .calc_input_wrapper
that are adding dynamicaly.
$(this).closest(".results").show().append(html)
This doesn't work.
<div class="calc_input_wrapper clearfix">
<ul class="calc_input_list clearfix">
<li class="product_number">1</li>
<li class="product_input">
<form method="post" action="do_search.php">
<input autocomplete="off" placeholder="Продукт" type="text" name="search" class='search_box'/>
</form>
<div class="delete_product_row"></div>
<ul class="results" class="update">
</ul>
</li>
<li class="product_weight">
<form action="">
<input autocomplete="off" type="text" placeholder="0">
</form>
</li>
<li class="product_protein">-</li>
<li class="product_fat">-</li>
<li class="product_carboh">-</li>
<li class="product_calor">-</li>
</ul>
</div>
$(document).on('keyup', '.search_box', function() {
// получаем то, что написал пользователь
var searchString = $(this).val();
// формируем строку запроса
var data = 'search=' + searchString;
// если searchString не пустая
if(searchString.length > 1) {
// делаем ajax запрос
$.ajax({
type: "POST",
url: "do_search.php",
data: data,
beforeSend: function(html) {
$(".results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){
//$(".results").show().append(html);
console.log('omg');
}
});
} else {
$(".results").html('');
}
return false;
});
$(this)
will not be same inside the ajax method' callback. Before the code which makes the call to $.ajax
method, this
represents the input box to which user entered some value. But inside the ajax method's success callback this
represent the xhr object. So i suggest you keep the $(this)
to a variable outside of your ajax call and use that.
Also you should use closest()
method to get to the outer li
element with css class "product_input" and use find()
method to get the result div.
var _this = $(this);
$.ajax({
//Your existing code
success: function(html){
_this.closest(".product_input").find(".results").show().html(html);
}
});
Another option is to use the context
property when making the ajax call. This will keep your this
as it is. So you can simply use $(this)
instead of the local variable.
$.ajax({
//your existing code
context: this,
success: function (html) {
$(this).closest(".product_input").find(".results").show().html(html);
}
});