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/
Related
I have a textfile in my project structure with 10 lines of names
Sarah
Adam
John
Connor
...
And I want to append all those lines as options to my as options
<select id="nameSelect">
<!-- I want them here -->
</select>
my question is.. Would I use pure JavaScript or something like React?
Because what if I wanted to add 100 items to the select, I wouldn't want to hardcode each option.
Here's a simple way of doing it with NodeJS, a popular server-side framework based on JavaScript. The page will be stored at the URL http://localhost:8080:
//For the purposes of this answer, your text file is called names.txt
var http = require("http");
var fs = require("fs");
http.createServer(function (req, res) {
fs.readFile("names.txt", function (err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("<select id='nameSelect'">
var namesArray = data.split("\n");
for (var i = 0; i < namesArray.length; i++) {
res.write("<option value='" + namesArray[i] + "'>" + namesArray[i] + "</option>");
}
res.write("</select>");
res.end();
});
}).listen(8080);
If the text file and the file with your options are on the same server, you can indeed show the options based on the text file's content using only JavaScript in the frontend. When your page loads use Ajax to retrieve the file content, and in your callback split by newline and add each line as an option.
<script>
window.onload = function() {
var client = new XMLHttpRequest();
client.open('GET', '/foo.txt');
client.onreadystatechange = function() {
var select = document.getElementById("nameSelect"),
options = client.responseText.split("\n"),
i,
_html = "";
for ( i = 0; i < options.length; i++ ) {
_html += "<option value=" + options[i] +">" + options[i] + "</option>";
}
select.innerHTML = _html;
}
client.send();
}
</script>
How to properly append json result to a select option,
sample json data
Ajax code:
$.ajax({
url: 'sessions.php',
type: 'post',
datatype: 'json',
data: { from: $('#datepicker_from').val().trim(), to: $('#datepicker_to').val().trim() },
sucess: function(data){
var toAppend = '';
//if(typeof data === 'object'){
for(var i=0;i<data.length;i++){
toAppend += '<option>'+data[i]['id']+'</option>';
}
//}
$('#sessions').append(toAppend);
}
});
html code:
<p>Sessions:
<select id="sessions"></select>
I already set to my php file
header("Content-Type: application/json");
Use $.each to iterate through your JSON array that you receive from ajax call.
Note:- the spelling of success, you have written sucess.
success: function(data){
var toAppend = '';
$.each(data,function(i,o){
toAppend += '<option>'+o.id+'</option>';
});
$('#sessions').append(toAppend);
}
You can do append to the DOM directly inside the each loop but it is always better to concatenate with string and then adding to the DOM later. This is a cheaper operation since you are accessing DOM only once in this case. This might not work in some complex scenarios though.
success: function(data) {
var options = "";
for (var i = 0; i < data.length; i++) {
options += "<option>" + data[i].id + "</option>";
}
$("#sessions").html(options);
}
If your response is in multidimensional array then try as follows
success: function(data) {
var options = '';
for (var i = 0; i < data.length; i++) {
for (var j = 0; j< data[i].length; j++){
options += '<option value="' + data[i][j].product_id + '">' + data[i][j].name + '</option>';
}
}
$("#products").html(options);
}
I hope this will help you to append
for(i=0; i<data.length; i++) {
$('#sessions').append("<option value="+data[i].id+"/option>");
}
Let You receive json data in parameter data
var obj = JSON.parse(data);
for(i=0; i<data.length; i++) {
$('#sessions').append("<option value="+obj[i].id+">"+obj[i].name+"</option>");
}
Please try the below code this may help you.
these code i used in spring boot MVC
JSON Data
[{"name":"Afghanistan","code":"af"},
{"name":"Albania","code":"al"},
{"name":"Algeria","code":"dz"}]
JQuery Code
var jsonData = '${restData}';
var obj = JSON.parse(jsonData);
for (i in obj) {
$('#selectList').append(new Option(obj[i].name, obj[i].code));
}
I link this JS page to an XML all element is views but the audio tag in xml file is not views in the html5 page ..any suggestion how to make this function retrieve the audio file and show it as html5 audi player.
init: function () {
//jQuery ajax call to retrieve the XML file
$.ajax({
type: "GET",
url: XMLLIST.xml,
dataType: "xml",
success: XMLLIST.parseXML
});
}, // end: init()
parseXML: function (xml) {
//Grab every single ITEM tags in the XML file
var data = $('item', xml).get();
//Allow user to toggle display randomly or vice versa
var list = (XMLLIST.random) ? XMLLIST.randomize(data) : data;
var i = 1;
//Loop through all the ITEMs
$(list).each(function () {
//Parse data and embed it with HTML
XMLLIST.insertHTML($(this));
//If it reached user predefined total of display item, stop the loop, job done.
if (i == XMLLIST.display) return false;
i++;
});
}, // end: parseXML()
insertHTML: function (item) {
//retrieve each of the data field from ITEM
var url = item.find('url').text();
var image = item.find('image').text();
var audio=item.find('audio').text();
var title = item.find('title').text();
var desc = item.find('desc').text();
var html;
//Embed them into HTML code
html = '<div class="item">';
html += '<a href="' + url + '"><image"' + image + '" alt="' + title + '" />';
html += '<span>' + title + '</span></a>';
html += '<audio control="control"><span> ' +audio+' </span></audio>';
html += '<p>' + desc + '</p>';
html += '</div>';
//Append it to user predefined element
$(html).appendTo(XMLLIST.appendTo);
}, // end: insertHTML()
randomize: function(arr) {
//randomize the data
//Credit to JSFromHell http://jsfromhell.com/array/shuffle
for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
return arr;
} // end: randomize()
}
AFAIK .each() is used to iterate over a jQuery object, if you want to iterate over an array use $.each()
Here you have
$(list).each(function () {
which should be
$.each(list, function () {
since list is an array of dom nodes and not a jQuery object
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
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.