JQuery two autocomplete text-fields - javascript

I don't know why if I have only one text field for categories the autocomplete is working (i can see suggested fill when user is typing in that categories text input box) but when I want to use more than one field let's say for subcategories it's not working on both (suggestions are not displaying)... Please help
<script type="text/javascript">
$.getJSON( {{ route('search.categories') }}, function( data ) {
var categories = data.map(function(val){
return val.title;
});
auto(categories);
});
$.getJSON( {{ route('search.subcategories') }}, function( data ) {
var subcategories = data.map(function(val){
return val.title;
});
auto(subcategories);
});
function auto(categories){
$("#category_input").autocomplete({
source: categories,
minLength: 2
});
}
function auto(subcategories){
$("#subcategory_input").autocomplete({
source: subcategories,
minLength: 2
});
}
</script>
View:
<input type="text" id="category_input" />
<input type="text" id="subcategory_input"/>

Try this:
<script type="text/javascript">
$.getJSON( {{ route('search.categories') }}, function( data ) {
var categories = data.map(function(val){
return val.title;
});
auto(categories);
});
$.getJSON( {{ route('search.subcategories') }}, function( data ) {
var subcategories = data.map(function(val){
return val.title;
});
auto_sub(subcategories);
});
function auto(categories){
$("#category_input").autocomplete({
source: categories,
minLength: 2
});
}
function auto_sub(subcategories){
$("#subcategory_input").autocomplete({
source: subcategories,
minLength: 2
});
}
</script>

Related

Facing Issue in ajax

I am new to laravel and ajax... i want to show the state of the selected country in dropdown list but when i select the country from the dropdown list it get data from the laravel perfectly and get it in ajax also.. but it is not able to append the data in html option tag.. for more details i am attaching the code of ajax also...`
$("#country").change(function(e){
var countryid = $(this).val();
console.log("Change Event Happpened on id : "+ countryid);
$.ajax({
type :"GET",
url :"GetStates/"+countryid,
success : function(statelist){
$("#state").empty();
$("#state").append('<option> Select State...</option>')
$.each(statelist,function (statename,stateid) {
**$("#state").append('<option>' + statename + ' </option>') // This line of code is not working**
console.log("in each function");
});
}
});
})
`
You're using jQuery.each function wrongly. jQuery.each callback function accepts two arguments:
Function( Integer indexInArray, Object value )
So according to your (wrong) code:
$.each(statelist,function (statename,stateid)
statename holds index of item and stateid receives statelist item, which clearly is against your idea.
Assuming that statelist has the following structure:
statelist = [
{
statename: 'LA',
stateid: 1
}
]
callback function should look like the following:
$.each(statelist,function (index, state) {
$("#state").append(`<option value="${state.stateid}">${state.statename}</option>`)
});
You can use javascript object destructuring to make this simpler:
$.each(statelist,function (index, {stateid, statename}) {
$("#state").append(`<option value="${stateid}">${statename}</option>`)
});
Working code:
const statelist = [{
statename: "LA",
stateid: 1
},
{
statename: "MA",
stateid: 2
},
];
$("#state").empty();
$("#state").append("<option value=''>Please select a state...</option>");
$.each(statelist, (index, {
statename,
stateid
}) => {
$("#state").append(`<option value="${stateid}">${statename}</option>`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="state">
<option>This will be removed</option>
</select>

Navigating a json file to create desired array for jquery autocomplete

I am programming an autocomplete function for a search bar that features names of places in Norway.
I collect the data from a REST api URL provided by a third party.
Example with input "st" and two results:
{
"sokStatus":{
"ok":"true",
"melding":""
},
"totaltAntallTreff":"81280",
"stedsnavn":[
{
"ssrId":"23149",
"navnetype":"By",
"kommunenavn":"Larvik",
"fylkesnavn":"Vestfold",
"stedsnavn":"Stavern",
"aust":"214841.84",
"nord":"6550500.29",
"skrivemaatestatus":"Godkjent",
"spraak":"NO",
"skrivemaatenavn":"Stavern",
"epsgKode":"25833"
},
{
"ssrId":"506202",
"navnetype":"By",
"kommunenavn":"Stord",
"fylkesnavn":"Hordaland",
"stedsnavn":"Stord",
"aust":"-32194.93",
"nord":"6665261.05",
"skrivemaatestatus":"Godkjent",
"spraak":"NO",
"skrivemaatenavn":"Stord",
"epsgKode":"25833"
}
]
}
I want to have the autocomplete array contain the "stedsnavn" features from all the returned results in the json file. so for the above example it would be [Stavern, Stord].
I built my code based off a template/tutorial i found online. When I run it now the autocomplete suggestion is the "totaltAntallTreff" feature so for the json above it would suggest 81280.
Edit: What I really need to know is how to properly query the json where I now only have response(data). I have tried several methods ($.map, $.each) but whenever I modify my code it ends up giving no autocomplete suggestions.
See my code below
$(function () {
var getData = function (request, response) {
$.getJSON(
"https://ws.geonorge.no/SKWS3Index/ssr/json/sok?antPerSide=5&eksakteForst=false&navn=" + request.term + "*",
function (data) {
(response(data));
});
};
var selectItem = function (event, ui) {
$("#myText").val(ui.item.value);
return false;
}
$("#myText").autocomplete({
source: getData,
select: selectItem,
minLength: 1,
change: function() {
$("#myText").val("").css("display", 2);
}
});
});
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery.ui.autocomplete.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<div id="menu-container">
<input type="text" id="myText" />
</div>
Given the JSON structure provided, you could get the result with the following:
let json_data = {
"sokStatus": {
"ok": "true",
"melding": ""
},
"totaltAntallTreff": "81280",
"stedsnavn": [{
"ssrId": "23149",
"navnetype": "By",
"kommunenavn": "Larvik",
"fylkesnavn": "Vestfold",
"stedsnavn": "Stavern",
"aust": "214841.84",
"nord": "6550500.29",
"skrivemaatestatus": "Godkjent",
"spraak": "NO",
"skrivemaatenavn": "Stavern",
"epsgKode": "25833"
},
{
"ssrId": "506202",
"navnetype": "By",
"kommunenavn": "Stord",
"fylkesnavn": "Hordaland",
"stedsnavn": "Stord",
"aust": "-32194.93",
"nord": "6665261.05",
"skrivemaatestatus": "Godkjent",
"spraak": "NO",
"skrivemaatenavn": "Stord",
"epsgKode": "25833"
}
]
}
let values = json_data.stedsnavn.map(item => item.skrivemaatenavn);
values.forEach(value => {
$("#list").append(`<li>${value}</li>`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="list"><ul>
As to what json_data.stedsnavn.map(item => item.skrivemaatenavn); is doing:
json_data.stedsnavn.map(item => item.skrivemaatenavn);
// Get the "stedsnavn" key from the data, an array
// Map each object in the array to
// its "skrivemaatenavn" key

Input field auto complete search select name and store the id in input box laravel

Using laravel and jquery for input field autocomplete. I need to select name and store the id of that user in input field.
<input id="show-user" type="text" class="typeahead form-control" name="student_code" value="{{ old('student_code') }}" placeholder="Student Code" required>
Here is javascript code
var path = "{{ url('library/issue-books/autocomplete/') }}";
$('input.typeahead').typeahead({
source: function (query, process) {
return $.get(path, { query: query }, function (data) {
return process(data);
});
}
});
Controller code for ptah
$data = User::where("name","LIKE","%{$request->input('query')}%")->get();
return response()->json($data);
Now my problem is when I select name, need to send student code in request. Student_code integer column.
You can send the input value to your route:
return $.get(path + $('#show-user').val(), {}, function (data) {
return process(data);
});
In this way you should have this route syntax:
/library/issue-books/autocomplete/{$query}
But you can pass just a query string also:
return $.get(path + '?query=' + $('#show-user').val(), {}, function (data) {
return process(data);
});

Autocomplete search form, search in the middle of texts

I am using the autocomplete to search the query.
In this source code, if you input ac you can get accepts, action_name.
However, I would like to get action_name with input name as a normal search form.
How can I make it?
$(function() {
var data = [
'accepts',
'action_name',
'add',
'add_column',
'add_index',
'add_timestamps',
'after_create',
];
$('#txtKeywd').autocomplete({
source: function(request, response) {
response(
$.grep(data, function(value){
return value.indexOf(request.term) === 0;
})
);
},
autoFocus: true,
delay: 500,
minLength: 2
});
});
$(function() {
var availableTags = [
'accepts',
'action_name',
'add',
'add_column',
'add_index',
'add_timestamps',
'after_create',
];
$("#tags").autocomplete({
source: availableTags
});
});
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
If you want to use the autocomplete plugin this will do it:
$(document).ready(function () {
var data = [
'accepts',
'action_name',
'add',
'add_column',
'add_index',
'add_timestamps',
'after_create',
];
$('#txtKeywd').autocomplete({
source: function(request, response) {
var re = $.ui.autocomplete.escapeRegex(request.term);
var matcher = new RegExp( re, "i" );
var a = $.grep( data, function(item,index){
return matcher.test(item);
});
response( a );
},
autoFocus: true,
delay: 500,
minLength: 2
});
});
You need to override the default regex used for autocomplete.
1 . Instead of just checking if the value is in the data element you can split the data element by - and _.
value.split(/-|_/)
2 . Then loop through it with a forEach() which takes as a parameter a function. e is the data element's value.
value.split(/-|_/).forEach(function(e) {});
3 . Then we just check if the input is in the e string
if(e.indexOf(request.term) === 0) {}
4 . If true and only if true we need to tell the grep() we're in that we have a successful match. To do so we need to set a boolean.
if(e.indexOf(request.term) === 0) { isIn = true; return; }
Above return; will end the search in the current split data element.
Here is the full code:
$(function() {
var data = [
'accepts',
'action_name',
'add',
'add_column',
'add_index',
'add_timestamps',
'after_create',
];
$('#tags').autocomplete({
source: function(request, response) {
response(
$.grep(data, function(value) {
let isIn;
value.split(/-|_/).forEach(function(e) {
if(e.indexOf(request.term) === 0) { isIn = true; return; }
});
return isIn
})
);
},
autoFocus: true,
delay: 500,
minLength: 2
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
Of course, this can be improved by splitting all the data values once on page load and store them in a special array to check.
Check this out
var data = [
'accepts',
'action_name',
'add',
'add_column',
'add_index',
'add_timestamps',
'after_create',
];
function split(val) {
return val.split(/ \s*/);
}
function extractLast(term) {
return split(term).pop();
}
$("#opt")
.autocomplete({
minLength: 0,
source: function(request, response) {
var term = request.term,
results = [];
term = extractLast(request.term);
if (term.length > 0) {
results = $.ui.autocomplete.filter(data, term);
}
response(results);
},
focus: function() {
return false; // prevent value inserted on focus
},
select: function(event, ui) {
}
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="ui-widget">
<label for="opt">Type Here:</label><br/>
<input id="opt" size="50">
</div>

sfWidgetFormDoctrineJQueryAutocompleter - events not working

I'm using the sfWidgetFormDoctrineJQueryAutocompleter from the sfFormExtraPlugin, an try to bind some event to the widget.
According to http://jqueryui.com/demos/autocomplete/#event-search there is a way to bind an event to the launch of a search.
However, it doesn't seems to work on the widget.
My code:
$this->widgetSchema['author_id'] = new sfWidgetFormDoctrineJQueryAutocompleter(array(
'model' => 'Employee',
'method' => 'getFullName',
'method_for_query' => 'findOneByEmployeeNumber',
'url' => '/backend_dev.php/employee/search',
'config' => '{
minChars: 3,
search: function(event, ui) { alert("Search!"); } //Should popup an alert() when the search is launched.
}'
));
However, when I fill the form, the search is launched, results are shown, but no alert is displayed.
Any ideas ?
Thanks.
Edit
Generated Javascript:
<label for="document_author_id">Author</label>
<input type="hidden" id="document_author_id" value="00000006" name="document[author_id]">
<input type="text" id="autocomplete_document_author_id" value="Michaƫl Jones" name="autocomplete_document[author_id]" autocomplete="off" class="ac_input">
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#autocomplete_document_author_id")
.autocomplete('/backend_dev.php/employee/search', jQuery.extend({}, {
dataType: 'json',
parse: function(data) {
var parsed = [];
for (key in data) {
parsed[parsed.length] = { data: [ data[key], key ], value: data[key], result: data[key] };
}
return parsed;
}
}, {
minChars: 3,
search: function(event, ui) { alert("Search!"); }
}))
.result(function(event, data) { jQuery("#document_author_id").val(data[1]); });
});
</script>
Try to put this at the end of your form.php (?) template
<?php javascript_tag(); ?>
jQuery().ready(function(){
// or use ID #autocomplete_document_author_id
jQuery(".ac_input").search(function(event, ui){
alert("Search!");
});
});
<?php end_javascript_tag(); ?>

Categories