I have three dropdowns which are depend on each other. Based on the selection of Dropdown A will have a list of results in Dropdown B, and based on the selection of Dropdown B will have a list of results in Dropdown C.
I can populate the first two dropdowns without a problem. However the last dropdown does shows me incorrect options.
$(function() {
var platforms;
var tasktypes;
var compos;
var jsonData;
$('#addnew').click(function(){
$('#dataset').clone().appendTo($('#newfield'));
});
$.getJSON('tasks.json', function(result) {
jsonData = result;
$.each(result, function(i, platform) {
platforms += "<option value='" +
platform.name +
"'>" +
platform.name +
"</option>";
});
$('#platform').html(platforms);
});
$("#platform").change(function (){
var idx = $("#platform").prop('selectedIndex');
var platforms = jsonData[idx].task;
tasktypes = "";
for (i = 0; i < platforms.length; i++) {
tasktypes += "<option value='" +
platforms[i].taskname +
"'>" +
platforms[i].taskname +
"</option>";
};
$('#taskname').html(tasktypes);
});
$("#taskname").change(function (){
var idc = $("#taskname").prop('selectedIndex');
var tasktypes = jsonData[idc].task[0].component;
compos = "";
for (i = 0; i < tasktypes.length; i++) {
compos += "<option value='" +
tasktypes[i].componentname +
"'>" +
tasktypes[i].componentname +
"</option>";
};
$('#components').html(compos);
});
});
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<button id="addnew">Add new</button>
<div id="dataset">
Platform:
<select id="platform">
</select>
Task Type:
<select id="taskname">
</select>
Component:
<select id="components">
</select>
Units:
<input type="number" min="0" />
</div>
<div id="newfield"></div>
<button id="calculate">Calculate</button>
<button id="clear">Clear</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>
Json
[
{
"name": "Sitecore",
"value": "sitecore",
"task": [
{
"taskname": "promobox",
"component": [
{
"componentname": "A",
"time": "20"
},
{
"componentname": "B",
"time": "10"
}
]
},
{
"taskname": "video",
"component": [
{
"componentname": "C",
"time": "20"
},
{
"componentname": "D",
"time": "10"
}
]
}
]
},
{
"name": "Siab",
"value": "siab",
"task": [
{
"taskname": "promobox",
"component": [
{
"componentname": "E",
"time": "20"
},
{
"componentname": "F",
"time": "10"
}
]
},
{
"taskname": "newswire",
"component": [
{
"componentname": "G",
"time": "20"
},
{
"componentname": "H",
"time": "10"
}
]
},
{
"taskname": "video",
"component": [
{
"componentname": "I",
"time": "20"
},
{
"componentname": "J",
"time": "10"
}
]
}
]
}
]
First two dropdowns works fine. Once I select a platform from the first dropdown, second dropdown populates with the relevant tasknames. But once I select a taskname from the second dropdown, third dropdown does show irrelevant data. I can't figure out what's wrong I'm doing here.
I believe the major problem you have is jsonData = result during the ajax request. All ajax requests are asynchronous by default, hence, every data produced from it is mostly non-existent after the request completion. So your best bet will be to pass result to the HTML DOM object during the request.
$.getJSON('tasks.json', function(result) {
$('#platform').data('jsonData',result);//Assign Json data to data object of platform id
$.each(result, function(i, platform) {
platforms += "<option value='" +
platform.name +
"'>" +
platform.name +
"</option>";
});
$('#platform').html(platforms);
});
Related
I'm trying to loop through some JSON data (var mydata) and mydata is an array of two elements, the second element in the array
mydata[1] is a multidimensional array, I need to display the first element i.e mydata[0] in a dt and display elements from mydata[1] in a dd within that.
I tried every option but I'm really stuck and I need any help on this. Below is my code:
var mydata = [
[{
"id": "67",
"name": "Baby & Toddler Clothing "
}, {
"id": "68",
"name": "Kids' Clothing, Shoes & Accessories"
}, {
"id": "69",
"name": "Costumes, Reenactment Theater"
}],
[
[{
"id": "572",
"name": "Baby Clothing Accessories "
}, {
"id": "573",
"name": "Baby Shoes"
}],
[{
"id": "579",
"name": "Boys Clothing [Sizes 4 & Up] "
}, {
"id": "580",
"name": "Boys Shoes"
}],
[{
"id": "588",
"name": "Costumes"
}, {
"id": "589",
"name": "Reenactment & Theater "
}]
]
]
function getCategories(id){
$.ajax({
url: '{$getcatUrl}',
type: 'POST',
data: {category_id: id},
success: function (data) {
data = jQuery.parseJSON(data);
//console.log(data); return;
if(data.length > 0){
firstdata = data[0];
secdata = data[1];
for(var i = 0; i < firstdata.length; i++) {
level_1 = firstdata[i].name;
level_1_id = firstdata[i].id;
for(var j = 0; j< secdata.length; j++){
if(secdata[i][j] !== undefined){
level_2='';
level_2 = secdata[i][j].name;
level_2_id = secdata[i][j].d;
}
console.log(level_2);
}
var dldata = $(
'<dl>'+
"<dt href='" + level_1_id + "'>" + level_1 + "</dt>"+
"<dd href='" + level_2_id + "'>" + level_2 + "</dd>"+
'</dl>'
);
}
}else{
console.log('no item for this categories');
}
},
error: function(jqXHR, errMsg) {
// handle error
console.log(errMsg);
}
});
}
The var level_1 and level_1_id works fine, but i keep getting error for variable level_2, the error says can't read property 'name' of undefined, any solution to this problem will be appreciated and am also open to new ideas about doing it better,
Essentially the problem is that you overwrite the level_1 and level_2 variables each time your for loops run. So by the time you get to the code which makes the HTML, they have been overwritten multiple times and only the last version remains, and you only print that once in any case.
This will resolve it - in this case by generating the HTML elements directly within each loop, although you could of course do it by appending to a variable and then outputting everything at the end, if that's your preference.
var data = [
[{
"id": "67",
"name": "Baby & Toddler Clothing "
}, {
"id": "68",
"name": "Kids' Clothing, Shoes & Accessories"
}, {
"id": "69",
"name": "Costumes, Reenactment Theater"
}],
[
[{
"id": "572",
"name": "Baby Clothing Accessories "
}, {
"id": "573",
"name": "Baby Shoes"
}],
[{
"id": "579",
"name": "Boys Clothing [Sizes 4 & Up] "
}, {
"id": "580",
"name": "Boys Shoes"
}],
[{
"id": "588",
"name": "Costumes"
}, {
"id": "589",
"name": "Reenactment & Theater "
}]
]
]
if (data.length > 0) {
var content = $("#content");
firstdata = data[0];
secdata = data[1];
for (var i = 0; i < firstdata.length; i++) {
var dl = $("#content").append("<dl/>");
dl.append("<dt href='" + firstdata[i].id + "'>" + firstdata[i].name + "</dd>");
for (var j = 0; j < secdata.length; j++) {
if (secdata[i][j] !== undefined) {
dl.append("<dd href='" + secdata[i][j].id + "'>" + secdata[i][j].name + "</dd>");
}
}
}
content.append(dl);
} else {
console.log('no item for this categories');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>
I'm trying to fill a dropdown list dynamically but it doesn't work. here is the code:
<form id="email-compose" class="form-email-compose" method="get" action="">
<div class="form-group">
<select id="input-to" class="input-transparent form-control">
</select>
</div>
<div class="form-group">
<input type="text" id="input-subject" placeholder="Subject" class="input-transparent form-control"
value="<%= subject %>">
</div>
<div class="form-group">
<textarea rows="10" class="form-control" id="wysiwyg" placeholder="Message"><%- body %></textarea>
</div>
<div class="clearfix">
<div class="btn-toolbar pull-xs-right">
<button type="reset" id="compose-discard-button" class="btn btn-gray">Annuler</button>
<button type="submit" id="compose-send-button" onClick="sendMail()" class="btn btn-danger"> Envoyer </button>
</div>
</div>
</form>
and the corresponding JS:
var jsonData = {
"Table": [{
"stateid": "2",
"statename": "Texas"
}, {
"stateid": "3",
"statename": "Louisiana"
}, {
"stateid": "4",
"statename": "California"
}, {
"stateid": "5",
"statename": "Nevada"
}, {
"stateid": "6",
"statename": "Massachusetts"
}]
};
$(document).ready(function () {
var listItems = '<option selected="selected" value="0">- Select -</option>';
for (var i = 0; i < jsonData.Table.length; i++) {
listItems += "<option value='" + jsonData.Table[i].stateid + "'>" + jsonData.Table[i].statename + "</option>";
}
console.log(listItems);
$("#input-to").html(listItems);
});
If I insert manually the option tags, I can see them correctly in the select but not dynamically...
I also tried with .append method but still having an empty drop down list.
Any idea ?
EDIT 1:
I also tried to use .append like this:
$(document).ready(function () {
$('#input-to').append('<option selected="selected" value="0">- Select -</option>');
for (var i = 0,opt; opt= jsonData.Table[i]; ++i) {
$('#input-to').append('<option value="' + opt.stateid + '">' + opt.statename + '</option>');
}
});
but same thing, my dropdown remains empty...
No problem of syntax as if I add manually the options I can see the options available.
one additional thing, my form is surrounded by a script:
<script type="text/template" id="compose-view-template">
....<form>
</script>
with the following js
var ComposeView = Backbone.View.extend({
template: _.template($('#compose-view-template').html()),
attributes: {
id: 'compose-view',
class: 'compose-view'
},
events: {
"click #compose-save-button, #compose-send-button, #compose-discard-button": 'backToFolders'
},
render: function() {
$('#widget-email-header').html(
'<h5>Nouvel <span class="fw-semi-bold">Email</span></h5>'
);
$('#folder-stats').addClass('hide');
$('#back-btn').removeClass('hide');
this.$el.html(this.template(this.model.toJSON()));
this._initViewComponents();
return this;
},
backToFolders: function(){
App.showEmailsView();
},
_initViewComponents: function(){
this.$("textarea").wysihtml5({
html: true,
customTemplates: bs3Wysihtml5Templates,
stylesheets: []
});
}
});
may be the js function is called when the form is not completely created ? hence, there is no action (and no error) because the form is not completely created ?
Your making a small mistake in your code
See the commeted out code below:
var jsonData = {
"Table": [{
"stateid": "2",
"statename": "Texas"
}, {
"stateid": "3",
"statename": "Louisiana"
}, {
"stateid": "4",
"statename": "California"
}, {
"stateid": "5",
"statename": "Nevada"
}, {
"stateid": "6",
"statename": "Massachusetts"
}]
};
$(document).ready(function () {
//
// Since your are adding the html to the element
// You dont need to recreate it!
//
// var listItems = '<option selected="selected" value="0">- Select -
// </option>';
var listItems="";
for (var i = 0; i < jsonData.Table.length; i++) {
listItems += "<option value='" + jsonData.Table[i].stateid + "'>" + jsonData.Table[i].statename + "</option>";
}
console.log(listItems);
$("#input-to").html(listItems);
});
Here is a fiddle of a working version
https://jsfiddle.net/40zz77ex/
Use .append instead of building HTML string. Something like this.
$(document).ready(function () {
$('#input-to').append('<option selected="selected" value="0">- Select -</option>');
for (var i = 0,opt; opt= jsonData.Table[i]; ++i) {
$('#input-to').append('<option value="' + opt.stateid + '">' + opt.statename + '</option>');
}
});
See working example
var jsonData = {
"Table": [{
"stateid": "2",
"statename": "Texas"
}, {
"stateid": "3",
"statename": "Louisiana"
}, {
"stateid": "4",
"statename": "California"
}, {
"stateid": "5",
"statename": "Nevada"
}, {
"stateid": "6",
"statename": "Massachusetts"
}]
};
$(document).ready(function() {
$('#input-to').append('<option selected="selected" value="0">- Select -</option>');
for (var i = 0, opt; opt = jsonData.Table[i]; ++i) {
$('#input-to').append('<option value="' + opt.stateid + '">' + opt.statename + '</option>');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="input-to"></select>
Hi (sorry for my english), I have this script:
<script type="text/javascript">
$(document).ready(function() {
var idPlato = decodeURI(getUrlVars()["idPl"]);
var url = "http://localhost/plato-datos.php?idPla="+idPlato+"";
});
};
</script>
It brings me this json from my database:
[{"category":"first","name":"green","idP":"1", "count":3},
{"category":"first","name":"blue","idP":"2","count":5},
{"category":"sec","name":"peter","idP":"3", "count":3},
{"category":"sec","name":"james","idP":"4", "count":2,},
{"category":"third","name":"dog","idP":"5", "count":4}]
I need to create one radiobuton for every name and group by categores
I create a solution. Kinda ugly but it will work:
var data = [{
"category": "first",
"name": "green",
"idP": "1",
"count": 3
}, {
"category": "first",
"name": "blue",
"idP": "2",
"count": 5
}, {
"category": "sec",
"name": "peter",
"idP": "3",
"count": 3
}, {
"category": "sec",
"name": "james",
"idP": "4",
"count": 2,
}, {
"category": "third",
"name": "dog",
"idP": "5",
"count": 4
}];
var result = {};
data.map(a => {
if (result[a.category]) {
result[a.category].push(a.name);
} else {
result[a.category] = [a.name];
}
});
Object.keys(result).map(category => {
var select = document.createElement('select');
result[category].map(name => {
var option = document.createElement('option');
option.value = name;
option.text = name;
select.appendChild(option);
});
document.body.appendChild(select);
});
Im working with jquery mobile then i used autodividersSelector function for group by the category JSON object, and build a radiobuton for every name
<script type="text/javascript">
//catch the JSON from my database
$(document).ready(function() {
var idPla = decodeURI(getUrlVars()["idPl"]);
var urlAder =
"http://localhost/lista-adereso.php?idPla=" + idPla + "";
//print the radiobutons
$.getJSON(urlAder, function(resultado) {
var allfiles = '';
for (var i = 0, aderesos = null; i <
resultado.length; i++) {
aderesos = resultado[i];
allfiles +='<li><label><input type="radio" data-
status="' + aderesos.aderesoCatNom +'"
name="name" id="id" value="' +
aderesos.aderNombre +'">'+
aderesos.aderNombre + '</label></li>'; }
//Group by categories
$('#linkList')
.empty()
.append(allfiles)
.listview({
autodividers:true,
autodividersSelector: function ( li ) {
var out = li.find('input').data("status");
return out;
}
})
.listview("refresh");
});
});
</script>
Below is sample JSON response. I need to parse this in a generic way instead of using transactionList.transaction[0].
"rateType": interestonly,
"relationshipId": consumer,
"sourceCode": null,
"subType": null,
"transactionList": {
"transaction": [
{
"amount": {
"currencyCode": "USD",
"value": 1968.99
},
"customData": {
"valuePair": [
{
"name": "valuePair",
"value": "001"
}
]
},
"dateTimePosted": null,
"description": "xyz",
"id": "01",
"interestAmount": {
"currencyCode": "USD",
"value": 1250
},
"merchantCategoryCode": 987654321,
"principalAmount": {
"currencyCode": "USD",
"value": 1823.8
},
"source": "Mobile Deposit",
"status": "Posted",
"type": "1"
}
]
},
I am using the following code to parse json
$.each(jsonDataArr, recursive);
function recursive(key, val) {
if (val instanceof Object) {
list += "<tr><td colspan='2'>";
list += key + "</td></tr>";
$.each(val, recursive);
} else {
if(val != null) {
if(!val.hasOwnProperty(key)) {
list += "<tr><td>" + key + "</td><td>" + val + "</td></tr>";
}
}
}
}
and this outputs as transactionList
transaction
0 and then the other keys & values. I was hoping to get transactionList and all the keys and values instead of getting the transaction and the array element. So I guess my parsing logic is not correct. Can anyone help me address this so I can just have the transactionList displayed? Thanks for your help inadvance.
It would help if we had an example of your desired results.
What if there are multiple transactions in the transactionList, how would it be displayed?
Essentially your issue is that Arrays are Objects as well.
http://jsfiddle.net/v0gcroou/
if (transactionList.transaction instanceof Object) == true
Key of transactionList.transaction is 0
Instead you need to also test if the object is an array, and do something else based on the fact you're now parsing an array instead of a string or JSON object
(Object.prototype.toString.call(val) === '[object Array]')
Another easy way would be to check the 'number' === typeof key since your JSON object does not contain numeric keys, but array objects inherently do.
http://jsfiddle.net/h66tsm9u/
Looks like you want to display a table with all your data. I added border=1 to the tables to visualize the boxes. See an example in http://output.jsbin.com/wuwoga/7/embed?js,output
function display(data) {
var html = "<table border='1'>";
var lists = recursive(data);
html += lists + "</table>";
return html;
}
function recursive(json) {
var list = "";
var instanceObj = false;
$.each(json, function(key, val){
instanceObj = (val instanceof Object);
list += [
"<tr>",
"<td>" + key + "</td>",
(instanceObj) ?
"<td><table border='1'>" + recursive(val) + "</table></td>" :
"<td>" + val + "</td>",
"</tr>"
].join("");
});
return list;
}
If you call display(json) with the json below, you'd get a display of all your data. If you add more data in the transaction array, it will display that too
var json = {
"rateType": "interestonly",
"relationshipId": "consumer",
"sourceCode": null,
"subType": null,
"transactionList": {
"transaction": [
{
"amount": {
"currencyCode": "USD",
"value": 1968.99
},
"customData": {
"valuePair": [
{
"name": "valuePair",
"value": "001"
}
]
},
"dateTimePosted": null,
"description": "xyz",
"id": "01",
"interestAmount": {
"currencyCode": "USD",
"value": 1250
},
"merchantCategoryCode": 987654321,
"principalAmount": {
"currencyCode": "USD",
"value": 1823.8
},
"source": "Mobile Deposit",
"status": "Posted",
"type": "1"
}
]
}
};
I need to fetch the values from this JSON in my java script this is coming from jsp:
[{
"selectionName": "Select",
"subSelections": [{
"id": 4,
"subSelectionName": "Select",
"description": "Deepmala"
}
]
}, {
"selectionName": "week14",
"subSelections": [{
"id": 7,
"subSelectionName": "1",
"description": ""
}
]
}, {
"selectionName": "test",
"subSelections": [{
"id": 6,
"subSelectionName": "test",
"description": ""
}
]
}, {
"selectionName": "select",
"subSelections": [{
"id": 3,
"subSelectionName": "sub-select",
"description": "Created by Prakash"
}
]
}, {
"selectionName": "testcreate",
"subSelections": [{
"id": 1,
"subSelectionName": "testcreate",
"description": ""
}
]
}, {
"selectionName": "by htmlwidget",
"subSelections": [{
"id": 5,
"subSelectionName": "by htmlwidget",
"description": "created by html widget"
}
]
}
]
Any suggestions? I am tring to fetch it like this:
function getSelection() {
var options = "";
$.getJSON('../r3/selection.jsp').done(function(json) {
//alert(json.selectionName);
// alert(json.subSelections);
// options += '<option value="' + value. selectionId + '">' + value.selectionName + '</option>';
$.each(json.subSelections, function(index, value) {
options += '<option value="' + value. subSelectionName + '">' + value. description + '</option>';
});
var select = $('<select id="selection" onchange="getSubselection()"/>');
select.append(options);
$(document.body).append(select);
}).fail(function (jqxhr, textStatus, error) {
alert(' fail json : '+error);
});
}
//alert(json.selectionName);
// alert(json.subSelections); inside the loop gives me undefined value.
Try this:
$.each(json, function (key, data) {
$.each(data.subSelections, function (index, values) {
options += '<option value="' + values.subSelectionName + '">' + values.description + '</option>';
});
});
var select = $('<select id="selection" onchange="getSubselection()"/>');
select.append(options);
$('body').append(select);