DropDown Menu Changing OnChange - html

I have 3 dropdown menu. and all 3 are interlinked. ie, if i select the values of 1st dropdown, depending on that the second dropdown should display values. depending on the selection of 2nd dropdown, 3rd dropdown should populate the values. have done for 1st and 2nd. but depending on the values of 2nd drop down am not able to populate the values of 3rd dropdown. can anyone plaz help me. i know something like this will be in JFIDDLE.com. but not able to fine the exact name to search that!

You have to use AJAX if you want that. it will be easy.
<select name="ID"
id="ID"
onchange="DoYourTaskHere(this);">
<option value="select" selected="selected">Select</option>
<c:forEach items="${A.List}" var="Variable">
<option value="${ID}">
<c:out value="${ID}" />
</option>
</c:forEach>
</select>
And in the script you write the code as follows.
function loadValue(ID) {
if (ID.value != "select") {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera,
// Safari
ValueXmlHttpReq = new XMLHttpRequest();
} else {// code for IE6, IE5
ValueXmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
ValueXmlHttpReq.onreadystatechange = processLoadValues;
ValueXmlHttpReq.open("POST", "getValue.htm?ID="
+ ID.value, true);
ValueXmlHttpReq.send();
} else {
var objSelect = document.getElementById("ValueId");
var currentValueListLength = objSelect.options.length;
while (currentValueListLength > 0) {
objSelect.remove(1);
currentValueListLength--;
}
var objSelect = document.getElementById("2ndDropDownWhereYouWantToPopulate");
var currentSecondValueListLength = objSelect.options.length;
while (currentSecondValueListLength > 0) {
objSelect.remove(1);
currentSecondValueListLength--;
}
}
}

Allright , here something to get you started :
<form name='cars'>
<select name='brand'></select>
<select name='model'></select>
</form>
​
and the javascript (i'm using jQuery ) :
var application_model = [
{
name: "General motors",
models: [
"model1", "model2", "model3"
]},
{
name: "Mercedes",
models: [
"model4", "model5", "model6"
]},
{
name: "Fiat",
models: [
"model7", "model8", "model9"
]}
];
var selectedBrandIndex = 0
var selectedModelIndex = 0
function render() {
// render the first combo
$('select[name=brand]').empty();
$.each(application_model, function(index, object) {
var selected = "";
if (index == selectedBrandIndex) {
selected = "selected";
}
console.log(this);
$('select[name=brand]').append("<option value='" + index + "' " + selected + ">" + object.name + "</option>");
})
// render the second combo
$('select[name=model]').empty();
$.each(application_model[selectedBrandIndex].models, function(index, object) {
var selected = "";
if (index == selectedModelIndex) {
selected = "selected";
}
console.log(this);
$('select[name=model]').append("<option value='" + index + "' " + selected + ">" + object + "</option>");
});
}
function main() {
$("select[name=brand]").bind("change", function(event) {
console.log(event.currentTarget.value);
selectedBrandIndex = event.currentTarget.value;
render();
});
render();
}
main();​
check the fiddle here :
http://jsfiddle.net/camus/MAgza/2/
cheers

you can try related combobox
You can easily setup any number of combobox instances on a single page. They can interact with each other based on certain client or server side events.
This example shows how the comboboxes can interact with each other using client-side methods and requesting the items on demand. To request the items on demand at the client-side, the requestItems() method is used.
The ViewState of the dependent comboboxes is disabled because the data required for their proper operation in this example is maintained in their ClientState.
refer http://demos.telerik.com/aspnet-ajax/combobox/examples/functionality/multiplecomboboxes/defaultcs.aspx

Related

Angular 2 Datalist Option click event in Angular 2 [duplicate]

I'm using a <datalist>
<datalist id="items"></datalist>
And using AJAX to populate the list
function callServer (input) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
//return the JSON object
console.log(xmlhttp.responseText);
var arr = JSON.parse(xmlhttp.responseText);
var parentDiv = document.getElementById('items');
parentDiv.innerHTML = "";
//fill the options in the document
for(var x = 0; x < arr.length; x++) {
var option = document.createElement('option');
option.value = arr[x][0];
option.innerHTML = arr[x][1];
//add each autocomplete option to the 'list'
option.addEventListener("click", function() {
console.log("Test");
});
parentDiv.appendChild(option);
};
}
}
xmlhttp.open("GET", "incl/search.php?value="+input.value, true);
xmlhttp.send();
}
However I can't get it to perform an action when I click on a selection in the datalist, for example if I type in "Ref F" and the item "Ref flowers" comes up, if I click on it I need to execute an event.
How can I do this?
option.addEventListener("click", function() {
option.addEventListener("onclick", function() {
option.addEventListener("change", function() {
Sorry for digging up this question, but I've had a similar problem and have a solution, that should work for you, too.
function onInput() {
var val = document.getElementById("input").value;
var opts = document.getElementById('dlist').childNodes;
for (var i = 0; i < opts.length; i++) {
if (opts[i].value === val) {
// An item was selected from the list!
// yourCallbackHere()
alert(opts[i].value);
break;
}
}
}
<input type='text' oninput='onInput()' id='input' list='dlist' />
<datalist id='dlist'>
<option value='Value1'>Text1</option>
<option value='Value2'>Text2</option>
</datalist>
This solution is derived from Stephan Mullers solution. It should work with a dynamically populated datalist as well.
Unfortunaltely there is no way to tell whether the user clicked on an item from the datalist or selected it by pressing the tab-key or typed the whole string by hand.
Due to the lack of events available for <datalist> elements, there is no way to a selection from the suggestions other than watching the input's events (change, input, etc). Also see my answer here: Determine if an element was selected from HTML 5 datalist by pressing enter key
To check if a selection was picked from the list, you should compare each change to the available options. This means the event will also fire when a user enters an exact value manually, there is no way to stop this.
document.querySelector('input[list="items"]').addEventListener('input', onInput);
function onInput(e) {
var input = e.target,
val = input.value;
list = input.getAttribute('list'),
options = document.getElementById(list).childNodes;
for(var i = 0; i < options.length; i++) {
if(options[i].innerText === val) {
// An item was selected from the list!
// yourCallbackHere()
alert('item selected: ' + val);
break;
}
}
}
<input list="items" type="text" />
<datalist id="items">
<option>item 1</option>
<option>item 2</option>
</datalist>
Use keydown
Contrary to the other answers, it is possible to detect whether an option was typed or selected from the list.
Both typing and <datalist> clicks trigger the input's keydown listener, but only keyboard events have a key property. So if a keydown is triggered having no key property, you know it was a click from the list
Demo:
const opts = document.getElementById('dlist').childNodes;
const dinput = document.getElementById('dinput');
let eventSource = null;
let value = '';
dinput.addEventListener('keydown', (e) => {
eventSource = e.key ? 'input' : 'list';
});
dinput.addEventListener('input', (e) => {
value = e.target.value;
if (eventSource === 'list') {
alert('CLICKED! ' + value);
}
});
<input type="text" id="dinput" list="dlist" />
<datalist id="dlist">
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
</datalist>
Notice it doesn't alert if the value being clicked is already in the box, but that's probably desirable. (This could also be added by using an extra tracking variable that will be toggled in the keydown listener.)
Datalist actually don't have an event (not all browsers), but you can detect if a datalist option is selected in this way:
<input type="text" list="datalist" />
<datalist id="datalist">
<option value="item 1" />
<option value="item 2" />
</datalist>
window.addEventListener('input', function (e) {
let event = e.inputType ? 'input' : 'option selected'
console.log(event);
}, false);
demo
Shob's answer is the only one which can detect when an option gets clicked as well as not trigger if an intermediary written text matches an option (e.g.: if someone types "Text1" to see the options "Text11", "Text12", etc. it would not trigger even if "Text1" is inside the datalist).
The original answer however did not seem to work on newer versions of Firefox as the keydown event does not trigger on clicks so I adapted it.
let keypress = false;
document.getElementById("dinput").addEventListener("keydown", (e) => {
if(e.key) {
keypress = true;
}
});
document.getElementById("dinput").addEventListener('input', (e) => {
let value = e.target.value;
if (keypress === false) {
// Clicked on option!
console.debug("Value: " + value);
}
keypress = false;
});
<input type="text" id="dinput" list="dlist" />
<datalist id="dlist">
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
</datalist>
Datalist don't support click listener and OnInput is very costly, checking everytime all the list if anything change.
What I did was using:
document.querySelector('#inputName').addEventListener("focusout", onInput);
FocusOut will be triggered everytime a client click the input text and than click anywhere else. If they clicked the text, than clicked somewhere else I assume they put the value they wanted.
To check if the value is valid you do the same as the input:
function onInput(e) {
var val = document.querySelector('#inputName').value;
options = document.getElementById('datalist').childNodes;
for(var i = 0; i < options.length; i++) {
if(options[i].innerText === val) {
console.log(val);
break;
}
}
}
<input type="text" id="buscar" list="lalista"/>
<datalist id="lalista">
<option value="valor1">texto1</option>
<option value="valor2">texto2</option>
<option value="valor3">texto3</option>
</datalist>
//0 if event raised from datalist; 1 from keyboard
let idTimeFuekey = 0;
buscar.oninput = function(){
if(buscar.value && idTimeFuekey==0) {
alert('Chévere! vino desde la lista')
}
};
buscar.onkeydown = function(event){
if(event.key){ //<-- for modern & non IE browser, more direct solution
window.clearInterval(idTimeFuekey);
idTimeFuekey = window.setInterval(function(){ //onkeydown --> idTimeFuekey++ (non 0)
window.clearInterval(idTimeFuekey);
idTimeFuekey = 0 //after 500ms onkeydown --> 0 (could work 500, 50, .. 1)
}, 500)
}
}
Well, at least in Firefox the onselect event works on the input tag
<input type="text" id="dinput" list="dlist" onselect="alert(this.value)"/>
<datalist id="dlist">
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
</datalist>
After having this problem and not finding a suitable solution, I gave it a shot.
What I did was look at the "inputType" of the given input event on top of the event toggle variable from above, like so:
eventSource = false;
const selector = document.getElementById("yourElementID");
selector.addEventListener('input', function(evt) {
if(!eventSource) {
if(evt.inputType === "insertReplacementText") {
console.log(selector.value);
}
}
});
selector.addEventListener('keydown', function(evt) {
eventSource = !evt.key;
});
This works if you want to allow the user to search a field but only hit a specific function/event on selection from the datalist itself. Hope it helps!
Edit: Forgot to mention this was done through Firefox and has not been tested on other browsers.

Google html creating a list from spreadsheet

I am trying to get a list to populate from a spreadsheet based on the question posted here Previous questioe posted by #Kron011and I'm struggling somewhat. I added these lines to my .gs file:
function getMenuListOne(){
return SpreadsheetApp.openbyId('spreadsheet_key').getSheetByName('sheet1')
.getRange(row, column, numRows, numColumns).getValues();
}
and I added these lines to my HTML file:
<select id="menu">
<option></option>
<option>Google Chrome</option>
<option>Firefox</option>
</select>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
// The code in this function runs when the page is loaded.
$(function() {
google.script.run.withSuccessHandler(showThings)
.getMenuListFromSheet();
google.script.run.withSuccessHandler(showMenu)
.getMenuListFromSheet();
});
function showThings(things) {
var list = $('#things');
list.empty();
for (var i = 0; i < things.length; i++) {
list.append('<li>' + things[i] + '</li>');
}
}
function showMenu(menuItems) {
var list = $('#menu');
list.find('option').remove(); // remove existing contents
for (var i = 0; i < menuItems.length; i++) {
list.append('<option>' + menuItems[i] + '</option>');
}
}
</script>
As ever my painfully limited experience is hampering my efforts. I can get a new menu box to appear and show the correct results I want but I cannot get an existing box to show the same list. The existing boxes code is currently:
<input type="text" name="site" list="depotslist" id="site" class="form-control" placeholder="Select depot/site" required>
<datalist id="depotslist">
<option value="one">
<option value="two">
</datalist>
but can someone please point me in the right direction of which parts of my existing menu box I need to change to get the two bits to communicate?
UPDATE 23 JULY
I added the following code to get the another list to operate from another source:
$(function() {
google.script.run.withSuccessHandler(showThings2)
.getMenuListSources();
google.script.run.withSuccessHandler(showMenu2)
.getMenuListSources();
});
function showThings2(things2) {
var list2 = $('#things2');
list.empty();
for (var i = 0; i < things2.length; i++) {
list2.append('<li>' + things2[i] + '</li>');
}
}
function showMenu2(menuItems2) {
var list2 = $('#menu2');
var box2 = $('#sourcelist');
list2.find('option').remove(); // remove existing contents
for (var i = 0; i < menuItems2.length; i++) {
list2.append('<option>' + menuItems2[i] + '</option>');
box2.append('<option>' + menuItems2[i] + '</option>');
}
}
with these lines in the .gs file:
var Bvals = SpreadsheetApp.openById(ssKey).getSheetByName('SourceCodes').getRange("C3:C").getValues();
var Blast = Avals.filter(String).length;
return SpreadsheetApp.openById(ssKey).getSheetByName('SourceCodes').getRange(3,3,Blast,1).getValues();
It would be similar to what you are doing with the element "menu". with jquery you can select the element of the box that contains the options and then append the new values. in this case it's id is: depotslist.
function showMenu(menuItems) {
var list = $('#menu');
var box = $('#depotslist');
list.find('option').remove(); // remove existing contents
for (var i = 0; i < menuItems.length; i++) {
list.append('<option>' + menuItems[i] + '</option>');
box.append('<option>' + menuItems[i] + '</option>');
}
As a difference with the element "menu" in this case the content will remain. This means that in the box you will see the options "one, two" and whatever you added because we are not removing the content like with this line
list.find('option').remove();
I'm not sure if this is exactly what you wanted to do, let me know if this doesn't help.

Unable to populate combobox using JSON response

I am using JQuery mobile for the first time. I want to populate a combobox from the JSON result. Here is the markup of the combobox:
<select name="comboChapters" id="comboChapters" data-native-menu="false">
</select>
The JSON response is like this:
[{"chapterId":1,"chapterName":"First"},{"chapterId":2,"chapterName":"Second"}]
And this is the JavaScript function I have written:
$(document).on('pagecreate', '#mainPage', function () {
var condition = navigator.onLine ? "ONLINE" : "OFFLINE";
if (condition === 'ONLINE') {
var options = '';
$.ajax({
url: '/GetChaptersList',
type: 'GET',
success: function (data) {//populate the combobox
for (var i = 0; i < data.length; i++) {
options += '<option value="' +
data[i].chapterId + '">' +
data[i].chapterName + '</option>';
}
$("#comboChapters").html(options);
},
});
}
else
alert('Please connect to the internet.');
});
The above code does not work. I have even tried the following code:
$(data).each(function() {
var option = $('<option />');
option.attr('value', this.chapterId ).text(this.chapterName );
$('#comboChapters').append(option);
});
Can someone point out how it can be done? I need the same functionality for checkbox list as well.
Populating the combobox appears to work. Check this:
<select name="comboChapters" id="comboChapters" data-native-menu="false">
var data = [{"chapterId":1,"chapterName":"First"},{"chapterId":2,"chapterName":"Second"}];
$(data).each(function() {
var option = $('<option />');
option.attr('value', this.chapterId ).text(this.chapterName );
$('#comboChapters').append(option);
});
http://jsfiddle.net/qsafmw5g/
Are you sure your request gets the data properly? Is "/GetChaptersList" the right URL?
Edit:
To make it work with jquery mobile you need to add this after the code that populates the options:
$('#comboChapters').selectmenu('refresh', true);
Edited jsfiddle: http://jsfiddle.net/qsafmw5g/1/

Use HTML5 (datalist) autocomplete with 'contains' approach, not just 'starts with'

(I can't find it, but then again I don't really know how to search for it.)
I want to use <input list=xxx> and <datalist id=xxx> to get autocompletion, BUT I want the browser to match all options by 'contains' approach, instead of 'starts with', which seems to be standard. Is there a way?
If not simply, is there a way to force-show suggestions that I want to show, not those that the browser matched? Let's say I'm typing "foo" and I want to show options "bar" and "baz". Can I force those upon the user? If I just fill the datalist with those (with JS), the browser will still do its 'starts with' check, and filter them out.
I want ultimate control over HOW the datalist options show. NOT over its UI, flexibility, accessibility etc, so I don't want to completely remake it. Don't even suggest a jQuery plugin.
If I can ultimate-control form element validation, why not autocompletion, right?
edit: I see now that Firefox does use the 'contains' approach... That's not even a standard?? Any way to force this? Could I change Firefox's way?
edit: I made this to illustrate what I'd like: http://jsfiddle.net/rudiedirkx/r3jbfpxw/
HTMLWG's specs on [list]
W3's specs on datalist
DavidWalsh example
HONGKIAT's summary on behaviors..?
'contains' approach
Maybe this is what you are looking for (part 1 of your question).
It goes with the limitation of "starts with" and changes when a selection is made.
'use strict';
function updateList(that) {
if (!that) {
return;
}
var lastValue = that.lastValue,
value = that.value,
array = [],
pos = value.indexOf('|'),
start = that.selectionStart,
end = that.selectionEnd,
options;
if (that.options) {
options = that.options;
} else {
options = Object.keys(that.list.options).map(function (option) {
return that.list.options[option].value;
});
that.options = options;
}
if (lastValue !== value) {
that.list.innerHTML = options.filter(function (a) {
return ~a.toLowerCase().indexOf(value.toLowerCase());
}).map(function (a) {
return '<option value="' + value + '|' + a + '">' + a + '</option>';
}).join();
updateInput(that);
that.lastValue = value;
}
}
function updateInput(that) {
if (!that) {
return;
}
var value = that.value,
pos = value.indexOf('|'),
start = that.selectionStart,
end = that.selectionEnd;
if (~pos) {
value = value.slice(pos + 1);
}
that.value = value;
that.setSelectionRange(start, end);
}
document.getElementsByTagName('input').browser.addEventListener('keyup', function (e) {
updateList(this);
});
document.getElementsByTagName('input').browser.addEventListener('input', function (e) {
updateInput(this);
});
<input list="browsers" name="browser" id="browser" onkeyup="updateList();" oninput="updateInput();">
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
Edit
A different approach of displaying the search content, to make clear, what happens. This works in Chrome as well. Inspired by Show datalist labels but submit the actual value
'use strict';
var datalist = {
r: ['ralph', 'ronny', 'rudie'],
ru: ['rudie', 'rutte', 'rudiedirkx'],
rud: ['rudie', 'rudiedirkx'],
rudi: ['rudie'],
rudo: ['rudolf'],
foo: [
{ value: 42, text: 'The answer' },
{ value: 1337, text: 'Elite' },
{ value: 69, text: 'Dirty' },
{ value: 3.14, text: 'Pi' }
]
},
SEPARATOR = ' > ';
function updateList(that) {
var lastValue = that.lastValue,
value = that.value,
array,
key,
pos = value.indexOf('|'),
start = that.selectionStart,
end = that.selectionEnd;
if (lastValue !== value) {
if (value !== '') {
if (value in datalist) {
key = value;
} else {
Object.keys(datalist).some(function (a) {
return ~a.toLowerCase().indexOf(value.toLowerCase()) && (key = a);
});
}
}
that.list.innerHTML = key ? datalist[key].map(function (a) {
return '<option data-value="' + (a.value || a) + '">' + value + (value === key ? '' : SEPARATOR + key) + SEPARATOR + (a.text || a) + '</option>';
}).join() : '';
updateInput(that);
that.lastValue = value;
}
}
function updateInput(that) {
var value = that.value,
pos = value.lastIndexOf(SEPARATOR),
start = that.selectionStart,
end = that.selectionEnd;
if (~pos) {
value = value.slice(pos + SEPARATOR.length);
}
Object.keys(that.list.options).some(function (option) {
var o = that.list.options[option],
p = o.text.lastIndexOf(SEPARATOR);
if (o.text.slice(p + SEPARATOR.length) === value) {
value = o.getAttribute('data-value');
return true;
}
});
that.value = value;
that.setSelectionRange(start, end);
}
document.getElementsByTagName('input').xx.addEventListener('keyup', function (e) {
updateList(this);
});
document.getElementsByTagName('input').xx.addEventListener('input', function (e) {
updateInput(this);
});
<input list="xxx" name="xx" id="xx">
<datalist id="xxx" type="text"></datalist>
yet this thread is posted about 2 years ago. but if you are reading this thread, you maybe need to check a newer version of your browser:
Current specification: https://html.spec.whatwg.org/multipage/forms.html#the-list-attribute
User agents are encouraged to filter the suggestions represented by
the suggestions source element when the number of suggestions is
large, including only the most relevant ones (e.g. based on the user's
input so far). No precise threshold is defined, but capping the list
at four to seven values is reasonable. If filtering based on the
user's input, user agents should use substring matching against both
the suggestions' label and value.
And when this post written, behavior of Firefox (51) and Chrome (56) had already been changed to match the specification.
which means what op want should just work now.
this fiddle here has cracked what you are asking for
But I am not sure how to make it work without this dependency as the UI looks bit odd and out of place when used along with Bootstrap.
elem.autocomplete({
source: list.children().map(function() {
return $(this).text();
}).get()
I found this question because I wanted "starts with" behavior, and now all the browsers seem to implement "contains". So I implemented this function, which on Firefox (and probably others), if called from input event handler (and optionally, from focusin event handler) provides "starts with" behavior.
let wrdlimit = prefix =>
{ let elm = mydatalist.firstElementChild;
while( elm )
{ if( elm.value.startsWith( prefix ))
{ elm.removeAttribute('disabled');
} else
{ elm.setAttribute('disabled', true );
}
elm = elm.nextElementSibling;
}
}

Problem in getting right result for select box

I am using jQuery as:
$(document).ready(function(){
test("price");
alert("hi");
$("#item2").change(function()
{
sort= $("#item2").val();
test(sort);
});
});
Function test() is some JavaScript function, my problem is when page loads function calls by "price" parameter. Now when I select some item from select box function test() is called using sort parameter (verify by alert box). but I am not getting the correct result. I mean when I select option from select box than also my result of test() is as with "price" , I suppose it might be the problem because of jQuery's $(document).ready(function(){,. test() function make some html code based on the parameter and show it on the web page.
Please suggest me what can be the solution
EDIT:
function test() is :
function test(sort)
{
<%
Ampliflex ms = Ampliflex.getInstance();
String solrIP = ms.getSolrIP();
String solrPort = ms.getSolrPort();
String rows = ms.getSearchResultCount();
%>
solrIP='<%= solrIP %>'; // get Solr IP address
solrPort='<%= solrPort %>'; // get Solr Port number
rows='<%= rows %>'; // get number of results to return
solrURL="http://"+solrIP+":"+solrPort;
var query="${searchStr}"; // get the query string entered by ECommerce user
query=query.replace(/[^a-zA-Z 0-9*?:.+-^""_]+/g,''); // Remove special characters
query=query.replace(/\*+/g,'*'); // Replace multiple occurrence of "*" with single "*"
var newquery=query;
if(parseInt(query)==NaN)
{
var lowerCaseQuery=query.toLowerCase();
newquery=lowerCaseQuery;
}
else{
var lowerCaseQuery=query;
}
// sort= document.getElementById("item2").value;
$.getJSON(solrURL+"/solr/db/select/?qt=dismax&wt=json&&start=0&rows="+rows+"&q="+lowerCaseQuery+"&hl=true&hl.fl=text&hl.usePhraseHighlighter=true&sort="+sort+" desc&json.wrf=?", function(result){
var highlight = new Array(result.response.numFound);
$.each(result.highlighting, function(i, hitem){
var rg = /<em>(.*?)<\/em>/g;
var res = new Array();
var match = rg.exec(hitem.text[0]);
while(match != null){
res.push(match[1])
match = rg.exec(hitem.text[0]);
}
highlight[i]=res[0]
for (j=1 ;j<res.length;j++)
{
highlight[i]= highlight[i]+","+res[j];
}
});
var html="<table><tr>"
var count=0;
var alt="NoImage";
var size="3pt";
var id;
var flag=1; // Flag for error messages
border="1";
// If no search results
if(result.response.numFound==0)
{
var msg= "<hr /><font size="+size+" >We're sorry, we found no results for <b>"+document.getElementById("queryString").value+"</font><hr />";
}
else
{
/* var msg= "<hr /><font size="+size+" >Total Results Found <b> "+ result.response.numFound+"</b> for "+"<b>"+document.getElementById("queryString").value+"</b> keyword</font><hr /> ";*/
if (newquery==lowerCaseQuery)
{
var msg= "<hr /><font size="+size+" >Total Results Found <b> "+ result.response.numFound+"</b> for "+"<b>"+query+"</b> </font><hr /> ";
}
else
{
var msg= "<hr /><font size="+size+" >There were no exact matches for <b> "+ query+"</b> , so we searched automatically for "+"<b>"+query+"</b> and yielded "+result.response.numFound+" result(s)</font><hr /> ";
}
// Parse solr response and display it on web page
$.each(result.response.docs, function(i,item){
var word = new Array();
word=highlight[item["UID_PK"]].split(",");
var result="";
var j=0;
for (j=0 ;j<=item.text.length;j++)
{
result = result+item.text[j]+"<br>";
}
for (j=0 ;j<word.length;j++)
{
result=result.replace(word[j],'<em>' + word[j] + '</em>');
}
html+="<td><table>";
var src=item.image;
id="id";
if(src!= null && src!= ""){
html+="<p><tr><td><br>"+"<img id= "+id+ " src="+src+ " border="+border+ " /></td></tr>";
count=count+1;
html += "<tr><td><b>ImagePath</b> "+ item.image+"</td></tr>";
}
// If not insert a default image
else
{
src="images/products/default.jpg";
html+="<tr><td><br><p>"+"<img id= "+id+ " src="+src+ " border="+border+" /></td></tr>";
count=count+1;
html += "<tr><td><b>ImagePath</b> "+"No image path found" +"</td></tr>";
}
html += "<tr><td>UID_PK: "+ item.UID_PK+"</td></tr>";
html += "<tr><td>Name: "+ item.name+"</td></tr>";
html+="<tr><td><b>Price: $"+item.price+"</td></tr>";
html+="<tr><td> "+result+"<br></td></tr>";
html+="</p></table></td>"
if(count%3==0)
{
html+="</tr>"
html+="<tr>"
}
});
html+="</table>"
}
$("#text_container").html(msg);
$("#result").append(html);
}
});
});
}
Your question isn't particularly clear, but your alert code only fires when the document is ready - it is not inside the "change" event function.
Try using the following to see what value is being returned when you change the select box:
$(document).ready(function(){
test("price");
$("#item2").change(function()
{
sort= $("#item2").val();
alert(sort);
test(sort);
});
});
When changing the select box, you should get an alert with the value you have chosen, which will help you understand why the test() function isn't functioning as you expect.
If you amend your question to include the HTML of the select box and the test() function itself I will amend my answer to help.
The JQuery code that you have posted is working fine. Demo: http://jsfiddle.net/DtnUr/
We need more details to figure out the issue, such as your HTML code and JS functions.