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>
Related
I am practicing a shopping cart list but I cannot populate the select I have tried several times but without success. Any guidance would be appreciated.
PHP:
$get_cart = mysqli_query($link,"SELECT cpro_id,cpro_name,cpro_price,cpro_qty FROM cart WHERE owner='$client'");
$rows = array();
while($r = mysqli_fetch_assoc($get_cart)) {
$rows[] = $r;
}
echo json_encode(array("status"=>"OK","data"=>$rows));
return true;
server response:
{"status":"OK","data":[
{"cpro_id":"9","cpro_name":"Product1","cpro_price":"10.00","cpro_qty":"1"},
{"cpro_id":"10","cpro_name":"Product2","cpro_price":"10.00","cpro_qty":"1"},
{"cpro_id":"11","cpro_name":"Product3","cpro_price":"10.00","cpro_qty":"1"},
{"cpro_id":"12","cpro_name":"Product4","cpro_price":"10.00","cpro_qty":"1"},
{"cpro_id":"13","cpro_name":"Product5","cpro_price":"10.00","cpro_qty":"1"}
]}
JS/HTML:
<select name="info" size="1" id="info" style="display:block;width: 100%;">
<option selected value="cpro_id">cpro_name</option>
</select>
<script>
$(document).ready(function() {
$.ajax({
method: "POST",
dataType: "JSON",
data: {
action: 'getcart'
},
url: "api.php"
})
.done(function(cart) {
//fill list
});
});
</script>
You can easily populate your json data with $.each like below example:
let obj = {
"status": "OK",
"data": [{
"cpro_id": "9",
"cpro_name": "Product1",
"cpro_price": "10.00",
"cpro_qty": "1"
},
{
"cpro_id": "10",
"cpro_name": "Product2",
"cpro_price": "10.00",
"cpro_qty": "1"
},
{
"cpro_id": "11",
"cpro_name": "Product3",
"cpro_price": "10.00",
"cpro_qty": "1"
},
{
"cpro_id": "12",
"cpro_name": "Product4",
"cpro_price": "10.00",
"cpro_qty": "1"
},
{
"cpro_id": "13",
"cpro_name": "Product5",
"cpro_price": "10.00",
"cpro_qty": "1"
}
]
};
$.each(obj.data, function(i, v) {
$('#info').append('<option value="' + v.cpro_id + '">' + v.cpro_name + '</option>')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="info" size="1" id="info" style="display:block;width: 100%;">
<option selected value="cpro_id">cpro_name</option>
</select>
In your code:
$.ajax({
method: "POST",
dataType: "JSON",
data: {
action: 'getcart'
},
url: "api.php"
})
.done(function(cart) {
$.each(cart.data, function(i, v) {
$('#info').append('<option value="' + v.cpro_id + '">' + v.cpro_name + '</option>')
});
});
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);
});
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>
The country and state will be sent as json
{
"data": [
{
"country": "USA",
"states": [
"Alabama",
"Alaska",
"Arizona"
]
},
{
"country": "India",
"states": [
"TN",
"AP",
"Mumbai"
]
}
]
}
There will be two select tags (country and state). How do I populate the states based on the country selected?
I am looking for a solution similar to http://www.datatables.net/examples/api/row_details.html where the row.data() returns the data set of a particular row.
Here's a very simple pure JavaScript way to populate two select boxes via JSON. In this example, State is dependent upon which Country is selected.
Example: http://jsfiddle.net/wasfd592/
HTML:
<select id="country">
<option>Country</option>
</select>
<select id="state">
<option>State</option>
</select>
JSON Object (assigned to variable d):
var d = {
"data": [
{
"country": "USA",
"states": [
"Alabama",
"Alaska",
"Arizona"
]
},
{
"country": "India",
"states": [
"TN",
"AP",
"Mumbai"
]
}
]
}
JavaScript:
// First - populate the Country select box from the JSON
for (var i in d.data) {
var elem = document.createElement("option");
elem.value = d.data[i].country;
elem.innerHTML = d.data[i].country;
document.getElementById("country").appendChild(elem);
}
// Next - add an event handler that will trigger when Country is changed and populate the State box
document.getElementById("country").addEventListener("change", function () {
document.getElementById("state").innerHTML = "";
var country = document.getElementById("country").options[document.getElementById("country").selectedIndex].value;
if (country === "Country") {
var elem = document.createElement("option");
elem.value = "State";
elem.innerHTML = "State";
document.getElementById("state").appendChild(elem);
}
for (var i in d.data) {
if (d.data[i].country === country) {
for (var a = 0; a < d.data[i].states.length; a++) {
var elem = document.createElement("option");
elem.value = d.data[i].states[a];
elem.innerHTML = d.data[i].states[a];
document.getElementById("state").appendChild(elem);
}
}
}
});
Try this out:- http://jsfiddle.net/ox4ykqoL/
HTML:-
<select id="country"></select>
<select id="states"></select>
JS:-
jQuery(function ($) {
var input = {
"data": [{
"country": "USA",
"states": [
"Alabama",
"Alaska",
"Arizona"]
}, {
"country": "India",
"states": [
"TN",
"AP",
"Mumbai"]
}]
};
$.each(input.data, function (index, d) {
$("#country").append("<option value=\"" + d.country + "\">" + d.country + "</option>");
});
$("#country").on("change", function () {
var selectedCountry = $("#country").val();
var t = $.map(input.data, function (obj) {
if (obj.country === selectedCountry) return obj;
});
if (t.length != 0) {
$('#states').empty();
debugger;
$.each(t[0].states, function (index, d) {
$("#states").append("<option value=\"" + d + "\">" + d + "</option>");
});
}
});
$("#country").change();
});
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);