I got the values from json and pass to the autocomplete search field.
[{"id":1,"name":"JAVA"},{"id":2,"name":"cake PHP"},"id":3,"name":"Android"}]
For example, when I click the JAVA, I want to get the id of JAVA like www.example.com/1
Jquery code:
<script>
$('#search').typeahead({
ajax: '/searchendpoint/search',
onSelect: function() {
window.location = "/home/view/" + $(this).val().id; }
});
</script>
When you want to use object array as a source you need to provide the logic for:
which object property to use for matching user input
which property to use for displaying text of the matching items
which property to use when user selects an item
More info:
http://api.jqueryui.com/autocomplete/#option-source
http://api.jqueryui.com/autocomplete/#method-_renderItem
http://api.jqueryui.com/autocomplete/#event-select
var tags = [
{"id":1,"name":"JAVA"},
{"id":2,"name":"cake PHP"},
{"id":3,"name":"Android"}
];
$( "#search" ).autocomplete({
source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
response( $.grep( tags, function( item ){
return matcher.test( item.name ); // match user request with item.name
}) );
},
select: function( event, ui ) {
event.preventDefault();
$("#search").val( ui.item.name ); // display user selection in textbox
console.log('selected: ' + JSON.stringify(ui) );
console.log('execute window.location = "example.com/' + ui.item.id + '"'); // use id of the selected item to generate required URL
}
});
// provide rendering logic for each matched item
$w = $( "#search" ).data("ui-autocomplete");
$w._renderItem = function( ul, item ) {
//console.log(JSON.stringify(item) );
return $( "<li>" )
.attr( "data-value", item.id )
.append( item.name )
.appendTo( ul );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<input id="search">
Edit: Using typeahead.js as per your comment.
var data =
[
{"id":1,"name":"JAVA"},
{"id":2,"name":"cake PHP"},
{"id":3,"name":"Android"}
];
$(function(){
var substringMatcher = function(strs) {
return function(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str.name)) {
matches.push(str);
}
});
cb(matches);
};
};
$('.typeahead').bind('typeahead:select', function(ev, suggestion) {
console.log('Selection: ' + JSON.stringify(suggestion) );
console.log('execute window.location = "example.com/' + suggestion.id + '"');
});
// passing in `null` for the `options` arguments will result in the default
// options being used
$('.typeahead').typeahead({
hint: true,
minLength: 1
}, {
source: substringMatcher(data),
display: 'name'
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>
<div id="prefetch">
<input class="typeahead" type="text" placeholder="">
</div>
More Info:
https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md
https://twitter.github.io/typeahead.js/examples/#the-basics
Please follow the solution as below.
HTML
<select id="search">
<option value="1">JAVA</option>
<option value="2">cake PHP</option>
<option value="3">Android</option>
</select>
Javascript
document.addEventListener('change', function(){
window.location = "www.example.com/" + document.getElementById('search').value;
})
Try this. Add event select on bind autocomplete.
$(function () {
var availableTags = [
{"id":1,"value":"JAVA"},
{"id":2,"value":"cake PHP"},
{"id":3,"value":"Android"}
];
$("#search").autocomplete({
source: availableTags,
select: function(event, ui) {
window.location = "www.example.com/" + ui.item.id;
}
});
});
I am not sure that I understand your question, but do you mean something like this?
JSON:
[{"id":1,"name":"JAVA"},{"id":2,"name":"cake PHP"},"id":3,"name":"Android"}]
jQuery:
<script>
var url = "http://example.com/";
$('#search').change(function() {
window.location = url + $(this).val().id;
});
</script>
onSelect function pass itemas variable you can use it in select event and it's structure like below
{
value: "1",
text: "Toronto"
}
and please try below code
<script>
$('#search').typeahead({
ajax: '/searchendpoint/search',
onSelect: function(item) {
//console.log(item);
window.location = "/home/view/" + item.value;
}
});
</script>
var data = [{
"id": 1,
"name": "JAVA"
}, {
"id": 2,
"name": "cake PHP"
}, {
"id": 3,
"name": "Android"
}]
var data_text = [];
var data_obj = [];
$.each(data, function(index, _data) {
data_text.push(_data.name);
data_obj[_data.name] = _data;
});
$('#search').typeahead({
source: data_text,
updater: function(item) {
alert(data_obj[item].id)
window.location = "/home/view/" + data_obj[item].id;
}
});
This is almost same answer as Vevik but just adjusted version of what the question actually wanted and tried to do. I have tested it.
<html>
<head>
<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>
<script>
$(function(){
var data = [{
"id": 1,
"name": "JAVA"
}, {
"id": 2,
"name": "cake PHP"
}, {
"id": 3,
"name": "Android"
}];
var data_labels = [];
var data_dictionay = [];
$.each(data, function(index, _data) {
data_labels.push(_data.name);
data_dictionay[_data.name] = _data.id;
});
$('#search').autocomplete({
source : data_labels,
select: function(ui, item) {
if(data_dictionay[item.item.value]){
window.location = "/home/view/" + data_dictionay[item.item.value];
}
}
});
});
</script>
</head>
<body>
<input id="search" type="text">
</body>
</html>
I dont know which typeahead you used, but i try to make an example
Try this:
$('#my-autoc').typeahead({
name: 'search',
remote: {
url: 'https://suggestqueries.google.com/complete/search?client=chrome&q=%QUERY',
dataType: 'jsonp',
cache: false,
filter: function(parsedResponse){
return (parsedResponse.length > 1) ? parsedResponse[1] : [] ;
}
}
}).on('typeahead:selected', function(e, data){
// its example
//window.location = "http://www.example.com/" + data.value
console.log("window.location = \"http://www.example.com/" + data.value + "\"")
// for your code
// window.location = "http://www.example.com/" + data.id
});
#import url('https://getbootstrap.com/dist/css/bootstrap.css');
#import url('https://rawgithub.com/jharding/typeahead.js-bootstrap.css/master/typeahead.js-bootstrap.css');
body{
padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://rawgithub.com/zeMirco/typeahead.js/master/dist/typeahead.min.js"></script>
<form id="my-form">
<input class="form-control" name="search" type="text" placeholder="type something ..." id="my-autoc">
<br>
</form>
Bootstrap's typeahead uses the properties label and value.
Try mapping your current array to these before passing it to typeahead.
results.map((item) => {
return {
"label": item.name,
"value": item.id
}
}
For various reasons, I need to be able to replicate an input box contextually. How does one initialize another typeahead.js instance every time a user adds another trip? I can't seem to initialize it with in the .on()
This is my current code:
html:
<form>
<div class="summary">
<div class="trip">
<input class="state tt-input">
... other code ...
</div>
...
</div>
<button type="button" id="add">Add another trip</button>
</form>
jquery:
$(document).ready(function() {
var additional = $('.trip').html();
$('form').on("change", '.state', function(e){
var $contextualDiv = $(e.target).closest('div');
var $state = $contextualDiv.find('.state');
});
$('#add').click(function() {
if ($('.summary').children().length >= 5) return;
$('.summary').append('<div class="trip">' + additional + "<div>");
});
$('.state').typeahead( //or $state.typeahead (that doesn't seem to work)
{
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
source: bh,
});
});
I suggest creating a function which will setup the typeahead for the given instance.
Then call that function for each newly created instance.
$(document).ready(function() {
var additional = $('.trip').html();
$('#add').click(function() {
if ($('.summary').children().length >= 5) return;
var new_trip = $('<div class="trip">' + additional + "<div>")
$('.summary').append(new_trip);
var state = new_trip.find('.state')
setupState(state)
});
setupState($('.state'))
});
function setupState(state){
state.typeahead(
{
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
source: bh,
});
}
I know some php/html/css but javascript is where I need help. I found on web autocomplete script, but this doesn't work on more than two input fields.
There are two problems I need to solve.
When you type in first box, autocomplete shows in second one. How to make script show autocomplete on box where user is typing?
I need to use the same autocomplete on multiple fields on my site.
The javascript syntax I use is:
var MIN_LENGTH = 2;
$( document ).ready(function() {
$("#keyword").keyup(function() {
var keyword = $("#keyword").val();
if (keyword.length >= MIN_LENGTH) {
$.get( "http://example.com/autofill/auto-complete.php", { keyword: keyword } )
.done(function( data ) {
$('#results').html('');
var results = jQuery.parseJSON(data);
$(results).each(function(key, value) {
$('#results').append('<div class="item">' + value + '</div>');
})
$('.item').click(function() {
var text = $(this).html();
$('#keyword').val(text);
})
});
} else {
$('#results').html('');
}
});
$("#keyword").blur(function(){
$("#results").fadeOut(500);
})
.focus(function() {
$("#results").show();
});
});
In order to re-use the same autocomplete code you need to give the scope of the function the context of the correct DOM element.
Here's a a quick jsfiddle with some simple HTML code, but it should give a basic example of how to bind the same events to multiple dom structures.
DEMO: JSfiddle example
JS
var MIN_LENGTH = 2;
$(document).ready(function() {
$(".keyword").keyup(function() {
var $parent = $(this).parent();
var $results = $parent.find('.results');
var keyword = $(this).val();
if (keyword.length >= MIN_LENGTH) {
$.get("/echo/json/", {
keyword: keyword
})
.done(function(data) {
$results.html('');
data = ['test', 'test2'];
//data = jQuery.parseJSON(data);
$(data).each(function(key, value) {
$results.append('<div class="item">' + value + '</div>');
});
});
} else {
$results.html('');
}
});
});
HTML
<div class="autcomplete">
<input class="keyword" />
<ul class="results"></ul>
</div>
<div class="autcomplete">
<input class="keyword" />
<ul class="results"></ul>
</div>
I'm trying to get the value of the dynamically generated radio button when this button is selected.
Here is my code snippet:
<div id="divContainer">
</div>
Jquery:
$("#divContainer").on("change", $('input[name="name1"]:checked'), function () {
var selectedVal=$('input[name="name1"]:checked').val();
console.log(selectedVal);
});
The value of the selectedVal is returning null here.
Resolution:
The default value was not properly assigned. I updated my code snippet which generates the radio button:
('#radiBtn').attr("value",val);
This resolved the issue.
Remove the $ wrapping from selector just use 'input[name="name1"]:checked't
for getting changed object use this
var div = $("#divContainer").on("change", 'input[name="name1"]:checked', function() {
var selectedVal = $(this).val();
console.log(selectedVal);
});
$('<input>', {
name: 'name1',
type: 'radio',
value: 1
}).appendTo(div);
$('<input>', {
name: 'name1',
type: 'radio',
value: 2
}).appendTo(div);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="divContainer">
</div>
I am trying to build a search that uses multiple drop downs. The script for the search uses the values for the first drop down and the second drop down. It works correct for Acura and MDX, but if I choose RLX it still passes MDX to the search as the value.
I know I have so somehow set for the value for the appended option to be whatever array is chosen in the second drop down, but I have had no luck. I am new to javascript so for all I know there may be a way easier than this to accomplish my goal.
FORM FOR SUBMIT
<form name="searchform" onSubmit="return dosearch();">
Brand:
<select id="brands">
<option val="Acura">Acura</option>
<option val="Chrysler">Chrysler</option>
</select>
<select id="item">
</select>
<input type="submit" value="Submit">
</form>
SCRIPT FOR URL STARTING WITH A BASE URL
<script type="text/javascript">
function dosearch() {
var sf=document.searchform;
var baseUrl = 'http://www.spitzer.com/new-inventory/index.htm?';
location.href = baseUrl.concat('make='+ sf.brands.options[sf.brands.selectedIndex].value + '&&&&' + 'model=' + sf.item.options[sf.brands.selectedIndex].value + '&&&&' );
return false;
}
SCRIPT FOR DROP DOWNS
// JavaScript Document
$(document).ready(function(){
Acura=new Array("MDX","RLX","ILX","TLX");
Chrysler=new Array('200','3000','Town&Country');
populateSelect();
$(function() {
$('#brands').change(function(){
populateSelect();
});
});
function populateSelect(){
cat=$('#brands').val();
$('#item').html('');
eval(cat).forEach(function(t) {
$('#item').append('<option val="">'+t+'</option>');
});
}
});
Wow wow!
Please read some code style for js. If it works it doesnt mean that it's good.
DO NOT USE eval, EVER! eval = evil
You forgetting var declaration.
Inline handler in html bad practice too.
forEach will break in IE <= 8
concat is good, plus is good too
... lot of mistakes, that will cost you after.
I`ve wrote you a one liner, but it doesnt have structure. Just some ideas and removed a lot of things.
http://jsfiddle.net/gwEP5/
Whole js code:
$(function (){
// Selector
var $form = $("#searchform");
// it could be hashchange in the future
var setPath = function (url) {
window.location = url;
};
var searchHandler = function (e) {
e.preventDefault();
// You can serialize whole form just by .serialize
var url = window.location.pathname + "?" + $form.serialize();
setPath(url);
};
// Handlers, set handlers in js not in DOM, inline delegation is really nasty
// alias for .submit
$form.on("submit", searchHandler);
// Form elements
var $brands = $('#brands'),
$item = $("#item");
// Items list, dont use new Array or String. It`s good way in
var items = {
"Acura": ["MDX","RLX","ILX","TLX"],
"Chrysler": ['200','3000','Town&Country']
};
// eval is EVIL !!!! don`t use it ever
var populateItems = function () {
var elements = "",
value = $brands.val();
if (items[value] != null) {
$.each(items[value], function (i, item) {
elements += "<option value=\"" + item + "\">" + item + "</option>";
});
}
$item.html(elements);
}
// Alias .change
$brands.on("change", populateItems);
// init for start
populateItems();
});
Html form:
<form name="searchform" id="searchform">
Brand:
<select id="brands" name="make">
<option value="Acura">Acura</option>
<option value="Chrysler">Chrysler</option>
</select>
<select id="item" name="model">
</select>
<input type="submit" value="Submit"/>
</form>
The setup itself is fine. However, you have a typo:
sf.item.options[sf.brands.selectedIndex]
Should be:
sf.item.options[sf.item.selectedIndex]
Or, if you prefer the more aesthetic jQuery:
function dosearch() {
var baseUrl = 'http://www.spitzer.com/new-inventory/index.htm?';
var brand = $('#brands').find(":selected").text();
var item = $('#item').find(":selected").text();
location.href = baseUrl + 'make=' + brand + '&&&&' + 'model=' + item + '&&&&';
return false;
}