Autocomplete search form, search in the middle of texts - javascript

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>

Related

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

JQuery two autocomplete text-fields

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>

Adjusting Datepicker

I have small knowledge of JS, but I was assigned a task to add some functionality to page. I need to add a datepicker in birthDate field, but once I add datepicker function to page my, validation(Jquery validation) stop working.
Here is code:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# page session="false"%>
<%# taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles"%>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://jqueryvalidation.org/files/demo/site- demos.css" />
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"> </script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<title>Parent Registration</title>
</head>
<body>
<!-- Everything inside should be the body -->
<tiles:insertDefinition name="defaultTemplate">
<tiles:putAttribute name="body">
....some code.........
<div class="form-group" >
<label for="birthDate" class="col-sm-3 control-label">Birthday</label>
<div class="col-sm-6">
<form:input type="text" class="form-control float_left" id="birthDate" name="birthDate" path="birthDate" placeholder="MM/DD/YYYY" required="true" />
</div>
</div>
...........some code...........
<script src="/resources/js/jquery.validate.min.js"></script>
<script src="/resources/js/validation.js"></script>
<script>
jQuery.validator.addMethod(
"dateUS",
function(value, element) {
var check = false;
var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if( re.test(value)){
var adata = value.split('/');
var mm = parseInt(adata[0],10);
var dd = parseInt(adata[1],10);
var yyyy = parseInt(adata[2],10);
var xdata = new Date(yyyy,mm-1,dd);
var currentTime = new Date();
var year = currentTime.getFullYear();
if ( ( xdata.getFullYear() == yyyy) && ( xdata.getFullYear() <= year ) && ( xdata.getMonth () == mm - 1 ) && ( xdata.getDate() == dd ) )
check = true;
else
check = false;
} else
check = false;
return this.optional(element) || check;
},
"Please enter a date in the format MM/DD/YYYY"
);
jQuery.validator.addMethod("parentName", function(value, element) {
return this.optional( element ) || /^(?=.*[a-zA-Z])([a-zA-Z.'-\s]+)$/.test( value );
}, 'The name should contain at least one alphabet character, space, dot, hyphen, apostrophe.');
$(document).ready(function(){
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$("#myform").validate({
rules: {
firstName: {
required: true,
parentName: true
},
middleName: {
parentName: true
},
lastName: {
required: true,
parentName: true
},
noOfChildren: {
required: true,
digits: true
},
birthDate: {
required: true,
dateUS: true
},
email: {
required: true,
email:true
},
confirmemail: {
required: true,
equalTo: "#email"
},
confirmpassword: {
required: true,
equalTo: "#password"
}
},
errorPlacement: function (label, element) {
if(element.is("input:checkbox")) {
element.parent("label").after( label );
} else if(element.is("input:radio")){
element.parent("label" ).parent("div:first").after( label );
}
else {
label.insertAfter( element );
}
},
submitHandler: function(form) {
form.submit();
}
});
});
</script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( "#birthDate" ).datepicker();
});
</script>
</tiles:putAttribute>
</tiles:insertDefinition>
</body>
</html>
You are including jquery 1.10.2 (at the bottom) and 1.11.3 (top) javascript files. This is most likely the problem.
Tipp: In Firefox you can debug your javascript and see error messages by pressing Ctrl+Shift+K or through Extras->Web-Developer->Web-Console.

Placeholder and on select in combobox

I have the following code which outputs me a combobox:
<html>
<head>
// Included JS library
</head>
<body>
<script>
$(document).ready(function ()
{
var moduleAutoSuggest = getModuleAutoSuggestOption();
// Create a jqxComboBox
$("#jqxWidget").jqxComboBox(
{
source: moduleAutoSuggest,
placeHolder : "text ...",
width: '250',
height: '25px',
disabled : false,
searchMode: 'containsignorecase',
autoComplete: true
});
obj = '';
$('#jqxWidget').on('select', function (event)
{
var args = event.args;
if (args != undefined) {
var item = event.args.item;
if (item != null)
{
obj = item;
printSelectedValue(obj);
}
}
});
});
function getModuleAutoSuggestOption()
{
var moduleAutoSuggestOption =
[
{"id" : "ALL_ICONS", "label":"All Icons"},
{"id" : "ALL_LOGOS", "label":"All Logos"},
{"id" : "ARTICLE", "label":"Newest Article"},
{"id" : "ARTICLE_SUMMARY", "label":"Headlines For 10 Newest Articles"}
];
return moduleAutoSuggestOption;
}
</script>
<div id='content'></div>
<div id='jqxWidget'>
</div>
</body>
</html>
It gives me a working combobox, the issue is, the placeHolder attribute is not working and If I click on the input text, the selected value doesnt get clearer
Any help will be appreaciated
Using your code, I created a working example that seems to be functioning identically to the jqwidgets example fiddle. Was there something about this functionality you were looking to change?
$(function ()
{
var moduleAutoSuggest = getModuleAutoSuggestOption();
// Create a jqxComboBox
$("#jqxWidget").jqxComboBox({
source: moduleAutoSuggest,
placeHolder: "text ...",
width: '250',
height: '25px',
disabled: false,
searchMode: 'containsignorecase',
autoComplete: true
});
obj = '';
$('#jqxWidget').on('select', function (event){
var args = event.args;
if (args != undefined) {
var item = event.args.item;
if (item != null)
{
obj = item;
printSelectedValue(obj);
}
}
});
});
function getModuleAutoSuggestOption()
{
return [
{"id" : "ALL_ICONS", "label":"All Icons"},
{"id" : "ALL_LOGOS", "label":"All Logos"},
{"id" : "ARTICLE", "label":"Newest Article"},
{"id" : "ARTICLE_SUMMARY", "label":"Headlines For 10 Newest Articles"}
];
}
<link href="http://www.jqwidgets.com/jquery-widgets-demo/jqwidgets/styles/jqx.base.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://www.jqwidgets.com/jquery-widgets-demo/jqwidgets/jqxcore.js"></script>
<script src="http://www.jqwidgets.com/jquery-widgets-demo/jqwidgets/jqxscrollbar.js"></script>
<script src="http://www.jqwidgets.com/jquery-widgets-demo/jqwidgets/jqxlistbox.js"></script>
<script src="http://www.jqwidgets.com/jquery-widgets-demo/jqwidgets/jqxbuttons.js"></script>
<script src="http://www.jqwidgets.com/jquery-widgets-demo/jqwidgets/jqxcombobox.js"></script>
<div id='content'></div>
<div id='jqxWidget'>
</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