Populate a Dropdown Menu with JSON Data - javascript

Attempting to populate a drop down menu with JSON data but cant quite figure out what I am doing wrong.
JSON Data
{"dropdownValue1":"1x1","dropdownDisplay1":"1x1","dropdownValue2":"1x2","dropdownDisplay2":"1x2","dropdownValue3":"1x3","dropdownDisplay3":"1x3","dropdownValue4":"1x4","dropdownDisplay4":"1x4","dropdownValue5":"1x5","dropdownDisplay5":"1x5","dropdownValue6":"1x6","dropdownDisplay6":"1x6"}
Java/HTML
<script type="application/javascript">
$(function(){
$("select#size").change(function(){
$.getJSON("getDropdown",{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + i + '">' + j[i] + '</option>';
}
$("select#size").append(options);
})
})
}) </script>
<div class="input select orderBoxContent">
<select name="size" id="size">
</select>
</div>
Actual JSON request
function getDropdown()
{
var people_no = $('#howmanypeople').val();
$.getJSON("../../getdata.php?getDropdown=yes&people_no="+people_no, function(response) {
$('#getDropdown').html(response.getDropdown);
});
}
Cheers
Ryan

Your JSON is an object but you are itterating it like an array.
var i;
for (i in j) {
if (j.hasOwnProperty(i)) {
// i = 'dropdownValue1'
// j[i] = "1x1"
// but the order is unknown
options += '<option value="' + j[i] + '">' + j[i] + '</option>';
}
}

$(function(){
$("select#size").change(function(){
$.getJSON("getDropdown",{id: $(this).val(), ajax: 'true'}, function(j){
var i;
for (i in j) {
if (j.hasOwnProperty(i)) {
// i = 'dropdownValue1'
// j[i] = "1x1"
// but the order is unknown
options += '<option value="' + j[i] + '">' + j[i] + '</option>';
}
}
$("select#size").append(options);
})
})
})

Related

How can I bind Jquery Ajax Json Reponses to a dropdown?

I'm trying to populate Json response from an Ajax call to a drop down and bind Name and UserID in a dropdown. Dropdown values all shows undefined. What I'm doing wrong here? Can you please help?
Dropdown DIV -
<div class="row form-group spacer">
<div class="col-md-12">
<div class="col-md-12">
#Html.Label("Recipients")
<select id="commentrecipients" class="dirtyignore" name="commentrecipients"></select>
</div>
</div>
</div>
Ajax Call -
$.ajax({
type: "GET",
url: "/Submission/SecurityGroupsUsersAccessRight",
data: {
id: 214
},
success: function (data) {
var s = '<option value="-1">Please Select a Recipient</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].UserID + '">' + data[i].Name + '</option>';
}
$("#commentrecipients").html(s);
}
});
Json Response -
data = "[{"SecurityGroupID":31,"SecurityGroupName":"Permission Testers","UserID":30,"Name":"Dawn Test'Neil"},{"SecurityGroupID":31,"SecurityGroupName":"Permission Testers","UserID":213,"Name":"Dawn 2 Bates"}]"
You need to parse the JSON data to get the object and then loop it.
ajax({
type: "GET",
url: "/Submission/SecurityGroupsUsersAccessRight",
data: {
id: 214
},
success: function (data) {
let response = JSON.parse(data);
var s = '<option value="-1">Please Select a Recipient</option>';
for (var i = 0; i < response.length; i++) {
s += '<option value="' + response[i].UserID + '">' + response[i].Name + '</option>';
}
$("#commentrecipients").html(s);
}
});
Try adding dataType: "json" and remove the "data:" ... something like this:
$.ajax({
type: "GET",
url: "/Submission/SecurityGroupsUsersAccessRight",
dataType: "JSON",
success: function (data) {
var s = '<option value="-1">Please Select a Recipient</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].UserID + '">' + data[i].Name + '</option>';
}
$("#commentrecipients").html(s);
}
});
Please try using the camel case property name:-
s += '<option value="' + data[i].userID + '">' + data[i].name + '</option>';
$.ajax({
type: "GET",
url: "/Submission/SecurityGroupsUsersAccessRight",
data: {
id: 214
},
dataType: "json",
success: function (data) {
$.each(data.d, function (i, val) {
var s = '<option value="-1">Please Select a Recipient</option>';
s += '<option value="' + val.UserID + '">' + val.Name + '</option>';
}
$("#commentrecipients").html(s);
}
});

How to stop earlier options of dependent dropdown list from showing up?

I am populating two dependent dropdown lists using an ajax call. The problem is that if I change my selection(master dropdown list) more than once, all the dependent options(the earlier values) show up in the dependent dropdown list. Here's my ajax call
$.ajax({
type: "GET",
url: "index.php?r=orders/on-select",
data: {myVar: myVar},
success: function (data) {
var jdata = JSON.parse(data);
var cluster = jdata.Clusters;
var sites = jdata.Sites;
$.each(cluster, function (optionValue, optionLabel) {
var option = $('<option value="' + optionLabel + '">' + optionLabel + '</option>');
$('[ref="region"]').find('[name="list box element"]').append(option);
var opnGrpval = $('<li value="' + optionValue + '">' + optionLabel + '</li>');
$('[ref="region"]').find('.selectBoxInput').find('.dropDownBox').append(opnGrpval);
});
$.each(sites, function (optionValue, optionLabel) {
var option = $('<option value="' + optionLabel + '">' + optionLabel + '</option>');
$('[ref="sites"]').find('[name="list box element"]').append(option);
var opnGrpval = $('<li value="' + optionValue + '">' + optionLabel + '</li>');
$('[ref="sites"]').find('.selectBoxInput').find('.dropDownBox').append(opnGrpval);
});
}
});
Change append to html then .
$.ajax({
type: "GET",
url: "index.php?r=orders/on-select",
data: {myVar: myVar},
success: function (data) {
var jdata = JSON.parse(data);
var cluster = jdata.Clusters;
var sites = jdata.Sites;
var regionOptions = '';
var dropdownOptions = ''
$.each(cluster, function (optionValue, optionLabel) {
var option = $('<option value="' + optionLabel + '">' + optionLabel + '</option>');
regionOptions += option;
var opnGrpval = $('<li value="' + optionValue + '">' + optionLabel + '</li>');
dropdownOptions += opnGrpval;
});
$('[ref="region"]').find('[name="list box element"]').html(listoptions); $('[ref="region"]').find('.selectBoxInput').find('.dropDownBox').html(dropdownOptions);
var sitesOptions = '';
var sitesDropdownOptions = '';
$.each(sites, function (optionValue, optionLabel) {
var option = $('<option value="' + optionLabel + '">' + optionLabel + '</option>');
sitesOptions += option;
var opnGrpval = $('<li value="' + optionValue + '">' + optionLabel + '</li>');
sitesDropdownOptions += opnGrpval;
});
$('[ref="sites"]').find('[name="list box element"]').html(sitesOptions); $('[ref="sites"]').find('.selectBoxInput').find('.dropDownBox').html(sitesDropdownOptions);
}
});

Fetching data from json inside listbox [duplicate]

I am having one dropdown and when I select one item from that dropdown a list appears corresponding to that item comes from a json in the list box. But I don't want to have list box, I want to have checkboxes so that I can select multiple items. I'm trying to convert this list box into checkboxes but not getting the intended result.. Please help!!!
This is my javascript code
$('#dropdown1').change(function () {
$('#listbox').empty();
$('<option>', {
text: 'Select your List Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#listbox');
var selection = $('#dropdown1 :selected').text();
// var selection = $('#dropdown1 :selected').text();
$.each(jsObject, function (index, value) {
if(value['name'] == selection) {
var optionHtml = '';
for(var i = 1; i <= 20; i++) {
var attr = 'attr' + ('000' + i).substr(-3);
optionHtml += '<option value="' + attr + '">' + value[attr] + '</option>';
}
$('#listbox').append(optionHtml);
return false;
}
});
});
This is my html code
<form name="myform" id="myForm">
<select id="dropdown1"></select>
<select id="listbox", multiple></select>
<br>
</form>
More js code
$(document).ready(function() {
$.ajax({
url: "data.json",
dataType: "json",
success: function(obj) {
var jsObject = obj;
var usedNames = [];
$('<option>', {
text: 'Select your Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#dropdown1');
$.each(obj, function(key, value) {
if (usedNames.indexOf(value.name) == -1) {
$("#dropdown1").append("<option value=" + key + ">" + value.name + "</option>");
usedNames.push(value.name);
}
After filling the dropdown with what you required, when u select an option the data u get instead of making a <select> make a <div>. Then fill the div with:
<input type="checkbox" name="yourDataName" value="yourDataName">yourDataName</input>
Check this demo on jsfiddle : https://jsfiddle.net/jagrati16/s566ss58/
This is just a demo. Hope it solves your problem
Change this:
$.each(jsObject, function (index, value) {
if(value['name'] == selection) {
var optionHtml = '';
for(var i = 1; i <= 20; i++) {
var attr = 'attr' + ('000' + i).substr(-3);
optionHtml += '<option value="' + attr + '">' + value[attr] + '</option>';
}
$('#listbox').append(optionHtml);
return false;
}
});
to this:
var check = '';
$.each(jsObject, function (index, value) {
if(value['name'] == selection) {
for(var i = 1; i <= 20; i++) {
var attr = 'attr' + ('000' + i).substr(-3);
check += '<input type="checkbox" name="'+attr+'" value="' + attr + '">' + value[attr] + '<br>';
}
$('#listbox').append(check);
}
});

for loop in multidimensional array on a selector for car shop

I have a selector for a car shop of make, model and year.
it no work fine... i only can select ALFA ROMEO and AUDI cars.
I think the problem is on my for inner loop.
$.each(carJson.marca, function (index, value) {
$("#marca").append('<option value="' + value.id + '">' + value.name + '</option>');
});
$('#marca').on('change', function () {
console.log($(this).val() ); // Marca.Id
for (var i = 0; i < carJson.marca.length; i++) {
if (carJson.marca[i].id == $(this).val()) {
$('#model').html('<option value="000">-Model-</option>');
$.each(carJson.marca[i].model, function (index, value) {
$("#model").append('<option value="' + value.id + '">' + value.name + '</option>');
});
}
$('#model').on('change', function(){
console.log($(this).val() );
for (var b=0; b < carJson.marca.length ; b++) {
for ( var c=0; c < 2 ; c++) {
//for ( var c=0; c < carJson.marca[b].model.length ; c++) {
if(carJson.marca[b].model[c].id == $(this).val()){
$('#eng').html('<option value="000">-Motorsss!-</option>');
$.each(carJson.marca[b].model[c].engine, function (index, value) {
$("#eng").append('<option value="' + value.id + '">' + value.name + '</option>');
});
}
}
}
} );
}
});
I Attached the code in jsFiddle: http://jsfiddle.net/LeqTn/
Thanks in advance.

Jquery adding and removing items from listbox

I've created this fiddle, it allows the user to click on either art or video, dynamically populating the the second listbox with the list associated with those selections. There are two buttons, one to add the selection to the box, the other which removes the selection.
What I would like to do is prevent the user from adding some that has already been added. The value of the options will all be Guids. Bonus points if you can modify the fiddle to use Guid instead of ints.
I've tried this:
$.each($("#SelectBox2 option:selected"), function (i, ob) {
if (i == $(this).val()) {
} else {
inHTML += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
}
});
I would like to enable the user to remove the selected items from the list.
Thanks,
UPDATE Just letting you guys know what the solution is that I came up with, I got the bonus points because i added GUID to it in a really smart way :) fiddle, I also tidied up the html to make it look nice and neat.
MAJOR UPDATE A massive thanks to everyone who has contributed to this question, I have taken on board everyones comments and fiddles and have generated this >> fiddle <<
I think you would want to do something like this: Check if value is in select list with JQuery.
Modifying your code to something like this should work:
$("#SelectBox2 option:selected").each(function () {
var optionVal = $(this).val();
var exists = false;
$('#SelectedItems option').each(function(){
if (this.value == optionVal) {
exists = true;
}
});
if(!exists) {
inHTML += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
}
});
Removing selected items would look like this:
$('#remove').click(function () {
$("#SelectedItems option:selected").remove();
});
If you want to dynamically add and delete rows seamlessly try this way
http://jsfiddle.net/WX4Nw/
Adding a pointer to the selecteditems list as a data attrib to the root item key will help you control so that you can easily manage add/remove.
Snippet from fiddle:-
$('#SelectBox').change(function () {
var str = "",
inHTML = "",
key = $('#SelectBox').val(),
items;
items = $(this).val() == 'art' ? artItems : vidItems;
$.each(items, function (i, ob) {
if($('#SelectedItems option[value="' + i + '"][data-key="' + key + '"]').length == 0)
inHTML += '<option value="' + i + '" data-key="' + key + '">' + ob + '</option>';
});
$("#SelectBox2").empty().append(inHTML);
});
$('#add').click(function () {
var itemsToAdd = [];
$("#SelectBox2 option:selected").each(function () {
var optionVal = $(this).val();
var key = $(this).data('key');
if ($('#SelectedItems option[value="' + optionVal + '"][data-key="' + key + '"]').length == 0) {
itemsToAdd.push($(this).removeAttr('selected'));
}
});
$("#SelectedItems").append(itemsToAdd);
});
Try:
$(function () {
var artItems = ["Art 1", "Art 2", "Art 3", "Art 4", "Art 5", "Art 6"];
var vidItems = ["Video 1", "Video 2", "Video 3", "Video 4", "Video 5", "Video 6"];
$('#SelectBox').change(function () {
var str = "",
inHTML = "",
items;
items = $(this).val() == 'art' ? artItems : vidItems;
$.each(items, function (i, ob) {
inHTML += '<option value="' + i + '">' + ob + '</option>';
});
$("#SelectBox2").empty().append(inHTML);
});
$('#SelectBox2').change(function () {
$("#selectedValues").text($(this).val() + ';' + $("#SelectBox").val());
$('#hidden1').val($(this).val());
});
$('#add').click(function () {
inHTML = "";
$("#SelectBox2 option:selected").each(function () {
if ($("#SelectedItems option[value=" + $(this).val() + "]").length == 0) {
inHTML += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
}
});
$("#SelectedItems").append(inHTML);
});
$('#remove').click(function () {
$('#SelectedItems option:selected').remove();
});
});
Fiddle here
Ok to fix your add function just add the following if condition::
if($("#SelectedItems option:contains("+$(this).text()+")").length<=0)
inHTML += '<option value="' + $(this).text() + '">' + $(this).text() + '</option>';
to remove items::
$('#remove').click(function () {
$("#SelectedItems option:selected").each(function () {
$(this).remove();
});
});
here is the example after i updated it jsfiddle
Have a look at this solution:- Using the data attribute to keep track of the items parent list selector and avoiding a loop with the help of this selector and data attribute.
http://jsfiddle.net/pramodsankar007/rMpBv/
$('#add').click(function () {
var itemsToAdd = [];
$("#SelectBox2 option:selected").each(function () {
var optionVal = $(this).val();
var key = $(this).data('key');
if($('#SelectedItems option[value="' + optionVal + '"][data-key="' + key +'"]').length == 0)
{
itemsToAdd.push($(this).removeAttr('selected').clone(true));
}
});
$("#SelectedItems").append(itemsToAdd);
});
});
SEE THE LINK
write if condition as
if($("#SelectedItems option:contains("+$(this).val()+")").length<=0)
inHTML += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
Then add
$('#remove').click(function(){
$('#SelectedItems :selected').each(function(i, selected) {
$(this).remove();
});
});
Get existing list of options, check if those you're adding already exist, if not, add them:
http://jsfiddle.net/bZXs4/
$('#add').click(function () {
var inHTML = "";
var $opts = $('#SelectedItems').find('option');
$("#SelectBox2 option:selected").each(function () {
var allowItemToBeAdded = true;
var selectedVal = $(this).val();
$opts.each(function(index, element){
if($(this).val() === selectedVal){
allowItemToBeAdded = false;
}
});
if(allowItemToBeAdded){
inHTML += '<option value="' + selectedVal + '">' + $(this).text() + '</option>';
}
});
if(inHTML !== ''){
$("#SelectedItems").append(inHTML);
}
});
try this if you want to prevent the user from adding an option that already exists
$("#SelectBox2 option:selected").each(function () {
if( $("#SelectedItems option[value='"+$(this).val()+"']").length <=0)
inHTML += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
})
http://jsfiddle.net/j2ctG/8/
Updated the fiddle for remove also.
Really Clean and Simple (works great and only a few lines):
$("#icon_move_right").click(function(){
$("#available_groups option:selected").each(function(){
available_group = $(this).val();
$("#assigned_groups").append("<option value='" + available_group + "'>" + available_group + "</option>");
});
$("#available_groups option:selected").remove()
});
$("#icon_move_left").click(function(){
$("#assigned_groups option:selected").each(function(){
assigned_group = $(this).val();
$("#available_groups").append("<option value='" + assigned_group + "'>" + assigned_group + "</option>");
});
$("#assigned_groups option:selected").remove()
});
$("#icon_move_right_all").click(function(){
$("#available_groups option").each(function(){
available_group = $(this).val();
$("#assigned_groups").append("<option value='" + available_group + "'>" + available_group + "</option>");
});
$("#available_groups option").remove()
});
$("#icon_move_left_all").click(function(){
$("#assigned_groups option").each(function(){
assigned_group = $(this).val();
$("#available_groups").append("<option value='" + assigned_group + "'>" + assigned_group + "</option>");
});
$("#assigned_groups option").remove()
});

Categories

Resources