get value from json and set to select option - javascript

Check my JQ code bellow. I have a json data like in data variable. And i want to loop though all of data and set value in html like example html. Can u help me to fix that? Thanks in advance
Html:
<select name="mainMenuSelect" id="mainMenuSelect">
<option value="MainMenuId">MenuName</option> //this output is my target
</select>
Jquery code:
var data = '{"MainMenuId":6,"MenuName":"T-Shairt","StoreId":1,"Store":null},{"MainMenuId":7,"MenuName":"Pants","StoreId":1,"Store":null},{"MainMenuId":9,"MenuName":"unixx","StoreId":1,"Store":null},{"MainMenuId":10,"MenuName":"things","StoreId":1,"Store":null}';
$.each(data, function (key, value) {
$('#mainMenuSelect').append('<option value=' + key + '>' + value + '</option>');
});

Your JSON format is invalid. Here is the working code
<select name="mainMenuSelect" id="mainMenuSelect">
<option value="MainMenuId">MenuName</option>
</select>
<script>
var data = [{"MainMenuId":6,"MenuName":"T-Shairt","StoreId":1,"Store":null},{"MainMenuId":7,"MenuName":"Pants","StoreId":1,"Store":null},{"MainMenuId":9,"MenuName":"unixx","StoreId":1,"Store":null},{"MainMenuId":10,"MenuName":"things","StoreId":1,"Store":null}];
var i = 0;
while(i < data.length){
document.getElementById("mainMenuSelect").innerHTML = document.getElementById("mainMenuSelect").innerHTML + "<option value='"+data[i]["MainMenuId"]+"'>"+data[i]["MenuName"]+"</option>";
i++;
}
</script>

your JSON is a string, you need to convert it to javascript object:
$.each(JSON.parse(data), function (key, value) {
$('#mainMenuSelect').append('<option value=' + key + '>' + value + '</option>');
});

You need to convert your data string into a valid json and then parse it to an object.
You also don't really need jQuery to add the options to the select.
var data = '{"MainMenuId":6,"MenuName":"T-Shairt","StoreId":1,"Store":null},{"MainMenuId":7,"MenuName":"Pants","StoreId":1,"Store":null},{"MainMenuId":9,"MenuName":"unixx","StoreId":1,"Store":null},{"MainMenuId":10,"MenuName":"things","StoreId":1,"Store":null}';
var options = JSON.parse('[' + data + ']');
var select = document.getElementById('mainMenuSelect');
options.forEach(function (option, i) {
select.options[i] = new Option(option.MenuName, option.MainMenuId);
});
<select name="mainMenuSelect" id="mainMenuSelect">
</select>

Here is your solution:
var data = [{"MainMenuId":6,"MenuName":"T-Shairt","StoreId":1,"Store":null},{"MainMenuId":7,"MenuName":"Pants","StoreId":1,"Store":null},{"MainMenuId":9,"MenuName":"unixx","StoreId":1,"Store":null},{"MainMenuId":10,"MenuName":"things","StoreId":1,"Store":null}]
$.each(data, function (key, value) {
$('#mainMenuSelect').append('<option value=' + value.MainMenuId + '>' + value.MenuName + '</option>');
});
demo

Related

Logging the selected from HTML list and use it as key in populating another

I'm trying to populate two dynamic Lists from two different JSON APIs , Where I need the first selected option to be used as the key to populate the second List.
HTML :
<p>
<input type="button" value="Fill SELECT Dropdown List with JSON" id="bt" />
</p>
<select id="clist" >
<option value="">-- Select --</option>
</select>
<select id="plist">
<option value="">-- Select --</option>
</select>
<p id="client_name"></p>
JS:
$(document).ready(function () {
$('#bt').click(function () {
var url1 = "https://script.google.com/macros/s/AKfycbx91EB9aIOXRYNmP108ZcPuEGgUqZWZli0KWdj5A3Ts0Qc6hrc/exec";
$.getJSON(url1, function (data) {
$.each(data, function (index, value) {
// APPEND OR INSERT DATA TO SELECT ELEMENT.
$('#clist').append('<option value="' + value.ID + '">' + value.Client + '</option>');
});
});
});
});
$('#clist').change(function () {
$('#client_name').text(this.options[this.selectedIndex].text);
var s_name=this.options[this.selectedIndex].text ;
});
$(document).ready(function () {
$('#clist').change(function () {
var url2 = "https://script.google.com/macros/s/AKfycbz91DIwPh3n4A7gtyV7iTrGxT7t23FMJES3n-ruvxHcfsFEXuBL/exec";
$.getJSON(url2, function (data2) {
$.each(data2, function (index2, value2) {
// APPEND OR INSERT DATA TO SELECT ELEMENT.
$('#plist').append('<option value="' + value2.ID + '">' + value2[s_name] + '</option>');
});
});
});
});
I was able to log the value and make a dynamic change and it works for the element Client_name but it doesn't work when populating the second list and returns undefined.
Note :
The selected option from the first key is exactly matching the available keys in the second list
Here is the solution for you question:
You need to just check if the key exists in value2 array.
Running code: https://jsfiddle.net/sfhogj7a/2/
Javascript:
var s_name =''; // make global
$(document).ready(function () {
$('#bt').click(function () {
var url1 = "https://script.google.com/macros/s/AKfycbx91EB9aIOXRYNmP108ZcPuEGgUqZWZli0KWdj5A3Ts0Qc6hrc/exec";
$.getJSON(url1, function (data) {
$.each(data, function (index, value) {
// APPEND OR INSERT DATA TO SELECT ELEMENT.
$('#clist').append('<option value="' + value.ID + '">' + value.Client + '</option>');
});
});
});
});
$('#clist').change(function () {
$('#client_name').text(this.options[this.selectedIndex].text);
s_name=this.options[this.selectedIndex].text ;
});
$(document).ready(function () {
$('#clist').change(function () {
console.log('list')
var url2 = "https://script.google.com/macros/s/AKfycbz91DIwPh3n4A7gtyV7iTrGxT7t23FMJES3n-ruvxHcfsFEXuBL/exec";
$.getJSON(url2, function (data2) {
$.each(data2, function (index2, value2) {
// APPEND OR INSERT DATA TO SELECT ELEMENT.
if(value2[s_name]){ // check if exists
$('#plist').append('<option value="' + value2.ID + '">' + value2[s_name] + '</option>');
}
});
});
});
});

How to create dropdown list using json data

I have pulled data from mysql table and decode json_decode now
we have json array for board,class,subject and they are related like parent ->child->grandchild(board->class->subject)
board_auto_id is first of classList json array class_auto_id is the first index of classSubjectList
Note : I have posted partial array of classList and classSubjectList
var boardList =[{"board_auto_id":"1","board_name":"CBSE"},{"board_auto_id":"2","board_name":"ICSE"},{"board_auto_id":"3","board_name":"NCERT"}];
var classList = {"1":[{"class_auto_id":"1","class_name":"VI"},{"class_auto_id":"2","class_name":"VII"},{"class_auto_id":"3","class_name":"VIII"},{"class_auto_id":"4","class_name":"IX"},{"class_auto_id":"5","class_name":"X"},{"class_auto_id":"6","class_name":"XI"},{"class_auto_id":"7","class_name":"XII"}]};
var classSubjectList = {"1":[{"class_auto_id":"1","sub_auto_id":"1","subject_name":"Science"},{"class_auto_id":"1","sub_auto_id":"2","subject_name":"Mathematics"},{"class_auto_id":"1","sub_auto_id":"3","subject_name":"Geography : The Earth Our Habitat "},{"class_auto_id":"1","sub_auto_id":"4","subject_name":"History : Our Pasts - I"},{"class_auto_id":"1","sub_auto_id":"5","subject_name":"Civics : Social And Political Life-I"},{"class_auto_id":"1","sub_auto_id":"86","subject_name":"English : Grammar"},{"class_auto_id":"1","sub_auto_id":"139","subject_name":"English : Writing Skills"},{"class_auto_id":"1","sub_auto_id":"155","subject_name":"English : Reading"},{"class_auto_id":"1","sub_auto_id":"209","subject_name":"संस्कृत : व्याकरण"},{"class_auto_id":"1","sub_auto_id":"220","subject_name":"Computer Science"},{"class_auto_id":"1","sub_auto_id":"235","subject_name":"Literature in English ( NCERT)"},{"class_auto_id":"1","sub_auto_id":"238","subject_name":"हिंदी व्याकरण"},{"class_auto_id":"1","sub_auto_id":"253","subject_name":"English : Vocabulary"}],"2":[{"class_auto_id":"2","sub_auto_id":"6","subject_name":"Science"},{"class_auto_id":"2","sub_auto_id":"7","subject_name":"Mathematics"},{"class_auto_id":"2","sub_auto_id":"8","subject_name":"Geography : Our Environment"},{"class_auto_id":"2","sub_auto_id":"9","subject_name":"History : Our Pasts - II"},{"class_auto_id":"2","sub_auto_id":"10","subject_name":"Civics : Social And Political Life - II"},{"class_auto_id":"2","sub_auto_id":"87","subject_name":"English : Grammar"},{"class_auto_id":"2","sub_auto_id":"140","subject_name":"English : Writing Skills"},{"class_auto_id":"2","sub_auto_id":"154","subject_name":"English : Reading"},{"class_auto_id":"2","sub_auto_id":"210","subject_name":"संस्कृत : व्याकरण"},{"class_auto_id":"2","sub_auto_id":"213","subject_name":"Computer Science"}]}
HTML code
<select name="boardId" id="boardId" class="style1"><option value="">Select Board</option></select>
<select name="classId" id="classId" class="style1"><option value="">Select Class</option></select>
<select name="subjectId" id="subjectId" class="style1"><option value="">Select Subject</option></select>
You can do something like this to bind json to dropdown
<select id="boardList"></select>
$.each(boardList, function (key, value) {
console.log(value.board_auto_id);
appenddata += "<option value = '" + value.board_auto_id + " '>" + value.board_name + " </option>";
});
$('#boardList').html(appenddata);
OnChange of boardList dropdown you need to filter records from another jsonArray and bind it to the next dropDown same as mentioned in above code.
first display board by using
jQuery.each(boardList, function(i , item) {
selectedBoard='';// if you display no board selected
boardListHtml += '<option '+ selectedBoard +' value="'+item.board_auto_id+'">'+item.board_name+'</option>';
});
jQuery('#boardId').html(boardListHtml);
create function for class and subject for each call
function getBoardByClass(boardId){
jQuery('#classId').html('');
var classChapterListHtml = '<option value="">Select Class</option>';
jQuery.each(classList, function(i , item) {
var selectedClass = (boardId ==item.class_auto_id) ? 'selected' : '';
classChapterListHtml += '<option '+ selectedClass +' value="'+item.class_auto_id+'">'+item.class_name+'</option>';
});
jQuery('#classId').html(classChapterListHtml);
}
function getSubjectByClass(classID){
jQuery('#subjectId').html('');
var subjectListHtml = '<option value="">Select Subject</option>';
jQuery.each(classSubjectList, function(id , subjectList) {
if (classID==id) {
jQuery.each(subjectList, function(subIds , subjectName) {
subjectListHtml += '<option value="'+subjectName.sub_auto_id+'">'+subjectName.subject_name+'</option>';
});
}
});
jQuery('#subjectId').html(subjectListHtml);
}
and finally change event for class and subject filter
$("#boardId").change(function() {
jQuery('#classId').html('');
getBoardByClass($(this).val());
});
$("#classId").change(function() {
jQuery('#subjectId').html('');
getSubjectByClass($(this).val());
});

Building HTML Selection field and selecting option with JavaScript Array

I have some JavaScript Arrays that are used to generate HTML selection fileds and then to also make the option a user has selected as the selected opton in the generated Selection list.
I have a working example for a basic JavaScript array. I need help with a more complex JS array though.
function buildFormSelection(optionArray, selectedOption){
var optionsHtml = '';
for(var i = 0; i < optionArray.length; i++){
optionsHtml += "<option value='" + optionArray[i] + "' "
+ (selectedOption == optionArray[i] ? "selected='selected'" : "")
+ ">" + optionArray[i] + "</option>";
}
return optionsHtml;
};
var typesArray = ['Other', 'SugarCRM', 'Magento', 'Design'];
console.log(buildFormSelection(typesArray, 'SugarCRM'));
This generates this HTML output...
<option value='Other'>Other</option>
<option value='SugarCRM' selected='selected'>SugarCRM</option>
<option value='Magento'>Magento</option>
<option value='Design'>Design</option>
Here is a JSFiddle to show it working. http://jsfiddle.net/jasondavis/4twd8oz1/
My issue is I now need to have the same functionality on a more complex array like this one below. It has an ID and a Name Value...
var milestonesArray = [
['1','Milestone 1'],
['2','milestone 2'],
]
Using similar code as my function above, I need to pull in a user's selected value from a database for example if they have saved the value of 2 then it should select selection option of 2 and show the text milestone 2 from a selection that looks like this...
<option value='1'>milestone 1</option>
<option value='2' selected='selected'>milestone 2</option>
I am not sure how to properly build a JavaScript array that can handle a key and value like this and make my function work with the milestone array.
Any help please?
What you need to do just add another array index to your function like so:
function buildFormSelection(optionArray, selectedOption){
var optionsHtml = '';
for(var i = 0; i < optionArray.length; i++){
optionsHtml += "<option value='" + optionArray[i][0] + "' "
+ (selectedOption == optionArray[i][0] ? "selected='selected'" : "")
+ ">" + optionArray[i][1] + "</option>";
}
return optionsHtml;
};
Where optionArray[i][0] is the value and optionArray[i][1] is the text.
JSFiddle
Answers with lots of code is usually frowned on but this is a trivial solution as #imtheman pointed out in his answer. But not everything needs to be so concise.
function makeOptionElement(value, title, selected) {
var option = document.createElement('option');
option.value = value;
if (selected) {
option.setAttribute('selected', 'selected');
}
option.innerHTML = title;
return option;
}
function dataToOptions(data, selectedIndex) {
var selectList = document.createElement('select');
data.forEach(function(item, index) {
var isSelected = (index === selectedIndex);
var option = makeOptionElement(item[0], item[1], isSelected);
selectList.appendChild(option);
});
return selectList;
}
Essentially, each time you call the array with your variables to be printed, you are calling the contents of the array in the position specified between the [ ]. It may be another array. That you can access as you would any other array. So, it would be:external_array[extrenal_array_index][internal_array_index]

set selected value of a drop down list

I have a dropdown list with values
function getTests() {
var html = '';
$.get('/getTests', function (tests) {
selTest = tests;
html +=' <option value="">SELECT</option>';
tests.forEach(function (test) {
html += '<option value="' + test.id + '">' + test.names + '</option>';
});
$('#testnames').html(html);
});
}
html code :-
<select class="lngcombo" id="testnames">
<option value="">SELECT</option>
<option value="25">email confirmation</option>
<option value="72">ttutu</option>
<option value="44">pagination</option>
</select>
while directing from another page am getting the value test.id as follows and want to get the value as selected in drop down
http://localhost:9080/history.html?testid=25
selected as the dropdown value email confirmation based on the testid=25
For that I am doing following :-
$(document).ready(function () {
if (window.location.href.indexOf('testid') > -1){
var testid = window.location.href;
testid =testid.split('=');
alert($("#testnames").val(testid[1]))
}
});
but not getting the value as selected
Since you are loading the contents using an ajax request, you need to set the value once the ajax request is completed and the options are created.
So solution template could look like
function getTests(testId) {
var html = '';
$.get('/getTests', function (tests) {
selTest = tests;
html += ' <option value="">SELECT</option>';
tests.forEach(function (test) {
html += '<option value="' + test.id + '">' + test.names + '</option>';
});
$('#testnames').html(html);
if(testId){
$("#testnames").val(testId)
}
});
}
$(document).ready(function () {
if (window.location.href.indexOf('testid') > -1) {
var testid = window.location.href;
testid = testid.split('=');
getTests(testid[1])
}else{
getTests()
}
});
You don't need the alert here, just use:
$("#testnames").val(testid[1]);
Fiddle Demo
Try this scripts.
JS
$(document).ready(function () {
if (window.location.href.indexOf('testid') > -1){
var testid = getParameterByName('testid');
$('#testnames').val(testid);
}
});
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
You need to call this function on complete of ajax call, the case is different here, the js-function calls first and html renders later. So it's important to understand that we should render html first and then call our js-function. It will works for you.
alert($("#testnames").val(testid[1]).val());
use this code
i have tested it
var val = $(".lngcombo").val(); alert(val);

Print contents of a list box as comma-separated values using JQuery

I have a select box defined as shown below. I want to print out the name and email address of each item in the select box as comma seperated values, like
Tom Wayne,tom#xyz.com
Joe Parker,joe#xyz.com
Peter Simons,peter#xyz.com
Any way to accomplish that using JQuery?
<select multiple="multiple" name="search_results">
<option value="tom#xyz.com">Tom Wane</option>
<option value="joe#xyz.com">Joe Parker</option>
<option value="peter#xyz.com">Peter Simons</option>
</select>
Thank You
I think is a good example to use Traversing/map:
$('select option').map(function () {
return $(this).text() + ',' + $(this).val();
}).get().join('\n');
Try this:
$("select").each(function() {
var options = [];
$(this).children("option").each(function() {
var $this = $(this);
options.push($this.text()+ "," + $this.val());
});
alert(options.join("\n"));
});
This will alert you the options for each select individually.
Something like this:
var s = "";
$("select option").each(function()
{
var $option = $(this);
s += $option.text() + ", " + $option.val() + "\n";
});
alert(s);

Categories