Подсказка при заполнении input на JS


Dram
660

Мне нужно чтобы при заполнении формы, данные искались в базе и предлагались к выбору.

Сам я JS не знаю, но на сайте у меня уже был похожий лайф поиск и я взял код оттуда и немного изменил:

jQuery(document).ready(function() {

jQuery(document).on('keyup', '#search', function(e) {
var name = jQuery(this).val();
if(name.length > 2) {
jQuery('#search-results').html('');
jQuery.ajax({
'type': 'GET',
'url': '/index.php',
'dataType': 'json',
'data': {
'option': 'com_form',
'view': 'item',
'format': 'json',
'task': 'search',
'name': name
},
'success': function (res) {
jQuery('.msg').html('');
jQuery('#search-results').html('');
jQuery.each(res, function (n, item) {
jQuery('#search-results').append('<div class="mod-row">'+ item.name +'</div>');
});
if(res) {
jQuery('#search-results').show();
}else{
jQuery('#search-results').hide();
}

}
});
}
});
});

Теперь все работает, слова находит — но как сделать чтобы по одному из найденных слов можно было кликнуть и оно бы вставилось в инпут формы?


ivan-lev

Гугл по autocomplete выдаст кучу вариантов.

Jquery autocomplete

https://jqueryui.com/autocomplete/


Dram

Я не знаю синтаксиса JS и не смогу вставить что-то без ошибок в свой код 🙁


Dram

Гуглил, читал, вот что понял из прочитанного.

Нужно из полученного ответа создать массив и передать его в форму.

Попытался сделать это так изменив действующий код (выделил жирным)

jQuery(document).ready(function() {
$("#search").autocomplete({
jQuery(document).on('keyup', '#search', function(e) {
var name = jQuery(this).val();
if(name.length > 2) {
jQuery('#search-results').html('');
jQuery.ajax({
'type': 'GET',
'url': '/index.php',
'dataType': 'json',
'data': {
'option': 'com_form',
'view': 'item',
'format': 'json',
'task': 'search',
'name': name
},
'success': function (res) {
jQuery('.msg').html('');
jQuery('#search-results').html('');
var suggestions = [];
jQuery.each(res, function (n, item) {
suggestions.push(item.name);
jQuery('#search-results').append('<div class="mod-row">'+ item.name +'</div>');
});
add(suggestions);
if(res) {
jQuery('#search-results').show();
}else{
jQuery('#search-results').hide();
}

}
});
}
});
});
});

В итоге и поиск перестал работать и автокомплит не заработал (((


Samail

Dram:
Гуглил, читал, вот что понял из прочитанного.

Нужно из полученного ответа создать массив и передать его в форму.

Нет наверное нужно сделать что-то вроде этого:


jQuery('#search-results').on('click', 'div.mod-row', function(e){
jQuery('#search').val( jQuery(this).text() );
});

Вместо #search селектор того инпута куда текст вставить нужно.


onep

Dram:
Гуглил, читал, вот что понял из прочитанного.

Про автокомплит что-то не дочитали. Примерно так должно быть


jQuery(document).ready(function() {

$("#search").autocomplete({
position: {
my: "left top",
at: "left bottom",
collision: "none",
offset: "1 4"
},
source: function (e, t) {


var name = jQuery(this).val();
jQuery('#search-results').html('');
jQuery.ajax({
'type': 'GET',
'url': '/index.php',
'dataType': 'json',
'data': {
'option': 'com_form',
'view': 'item',
'format': 'json',
'task': 'search',
'name': name
},
'success': function (e) {

t($.map(e, function (e) {
return {
name: e.name,
}
}))


}
});

},
minLength: 2
}).data("ui-autocomplete")._renderItem = function (e, t) {
return $("<li></li>").data("item.autocomplete", t).append("<i class="">" + t.name + "</i>").appendTo(e);
};


});


Dram

В итоге методом тыка сделал так, выкинул лишнее, внутри все собираю пушем в архив, а автокомплит отдельной функцией, все работает:

  var suggestions = [];
function nameSearch()
{
$( "#search" ).autocomplete({
source: suggestions
});
}


jQuery(document).ready(function() {
jQuery(document).on('keyup', '#search', function(e) {
var name = jQuery(this).val();
if(name.length > 2) {
jQuery('#search-results').html('');
jQuery.ajax({
'type': 'GET',
'url': '/index.php',
'dataType': 'json',
'data': {
'option': 'com_form',
'view': 'item',
'format': 'json',
'task': 'search',
'name': name
},
'success': function (res) {
jQuery('.msg').html('');
jQuery('#search-results').html('');
jQuery.each(res, function (n, item) {
suggestions.push(item.name);
});
}
});
}
});
});

и в инпут еще добавил

onkeydown=»nameSearch()»


onep

Проще же можно _jsfiddle.net/60v9ebmw/


Dram

onep, а как в ваш последний пример корректно вставить?

jQuery.ajax({
‘type’: ‘GET’,
‘url’: ‘/index.php’,
‘dataType’: ‘json’,
‘data’: {
‘option’: ‘com_form’,
‘view’: ‘item’,
‘format’: ‘json’,
‘task’: ‘search’,
‘name’: name
},

И еще вопрос — трижды встречающееся #search — это id инпута?


onep

Dram:
как в ваш последний пример корректно вставить?

Так же как и в вашем коде вставляйте _jsfiddle.net/m01g92j4/1/

Dram:
трижды встречающееся #search — это id инпута?

Да, <input id=»search» type=»text» />


ivan-lev

Ваш

$.ajax({

и

jQuery.ajax({

из примера — это одна и та же функция. Судя по коду, как-то так должно сработать.


jQuery(document).ready(function($) {
$("#search").autocomplete({
source: function(e, t) {
$.ajax({
'type': 'GET',
'url': '/index.php',
'dataType': 'json',
'data': {
'option': 'com_form',
'view': 'item',
'format': 'json',
'task': 'search',
'name': name
},
'success': function(e) {
t($.map(e, function(e) {
return {
value: e.name,
}
}))
}
})
},
minLength: 3,
select: function (t, n) {
$("#search").val(n.item.value)
}
}).data("ui-autocomplete")._renderItem = function(e, t) {
return $("<li></li>").data("item.autocomplete", t).append(t.value).appendTo(e);
}
});
Dram:
трижды встречающееся #search — это id инпута?

Именно оно.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *