How to create dropdown list using json data - javascript

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());
});

Related

get value from json and set to select option

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

Laravel 5.2 Dynamic dropdown select not populating (javascript)

I have two selects country, and information. The selected_country variable is passed to getInfo() which queries all rows matching that country and returns the deptname and id. The id is the option value in the select and is stored in the database,and deptname is the text displayed in the select. Right now my info dropdown is empty and I am not getting any errors.
public function getInfo()
{
$country = Input::get('selected_country');
$info = Department::where('addressCountry', $country)->orderBy('country')->pluck('deptname', 'id');
return response()->json($info);
}
route
Route::get('related-info', ['as' => 'related-info', 'uses' => 'Auth\AuthController#getInfo']);
Javascript
$('#addressCountry').on('change', function (e) {
var slots = $('#info');
slots.empty();
var selected_country = e.target.value;
$.get("related-info?selected_country=" + selected_country, function (data) {
slots.empty();
console.log(data);
$.each(data.slots, function (index, value) {
slots.append('<option value="' + value.id + '">' + value.name + '</option>');
});
});
});
Relavent parts of my view
<form class="form-horizontal" role = "form" method = "POST" action = "{{ url('/register') }}" > {!!csrf_field() !!}
<select class="form-control" name = "addressCountry" id = "addressCountry" ></select >
<select class="form-control" name = "addressProv" id = "addressProv" ></select >
<select id="info" class="form-control" name="info">
<option value=""></option>
</select>
Also in my view in the scrips section
populateCountries('addressCountry', 'addressProv');
The country and state drop downs are populated using a javascript file its too large to paste here
http://pastebin.com/9XUTPEVY
EDIT: After returning a json response in getInfo instead of the view, if I navigate directly to related-info?selected_country=Ireland it will show the id and name of each one. If I goto /register and select Ireland in the dropdown the dropdown does not populate but the response tab in the network console in firedebug shows the id and name of each. I also changed console.log(data); to alert(data) the pop up says [object Object] when selecting Ireland.
Here are 3 screenshots of output
http://imgur.com/a/jEfuu
All seems right except that you return a view instead of a Json object as response.
Try to replace:
return view('auth.register', ['info' => $info]);
With:
return response()->json($info);
Change the javascript code to this :
$('#addressCountry').on('change', function (e) {
var selected_country = e.target.value;
$.get('related-info?selected_country=' + selected_country, function (data) {
console.log(data);
$('#deptInfo').empty();
$.each(data, function (index, subcatObj) {
$('#info').append('<option value="' + subcatObj.id + '">' + subcatObj.name + '</option>');
});
});
})
I see that when you are going directly to the url, you are going to : related-info?selected_country=Ireland but in javascript, you go to:
related-info?country=' + selected_country but I guess you need to go to : related-info?selected_country

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]

Complete select list with optgroup in jquery

I have a select list that I complete by this way :
$.each(data, function(index, value) {
$('#Cars').append('<option value="'+ index +'">'+ value +'</option>');
});
The data table look like this : [{"0":"Ford","285":"Ferrari", "427":"Other"}]
I want now add category in my select list. The table will look like this
["Cars":{"0":"Ford","285":"Ferrari", "427":"Other"},"Tractors":{"114":"Ferguson","115":"Others"}}]
Can you help me to make the jquery code I have try some but with no result.
I want my select box look like this in Html :
<optgroup label="Cars">
<option>Ford</option>
<option>Ferrari</option>
<option>Other</option>
</optgroup>
<optgroup label="Tractors">
<option>Ferguson</option>
<option>Other</option>
</optgroup>
You can try loop through your nested hash:
var select = '';
$.each(data, function(key, value) {
select += '<optgroup label="'+ key +'">'
$.each(value, function(k, v) {
select += '<option value="'+ k +'">'+ v +'</option>'
})
select += '</optgroup>'
});
Fiddle
Here is a demo
your initial data should be properly formatteed associative array:
var items = {"Cars":{"0":"Ford","285":"Ferrari", "427":"Other"},"Tractors":{"114":"Ferguson","115":"Others"}};
and using 'for in' loop you solve your task.
for(catName in items)
{
var optGroup = $("<optgroup />", {
label: catName
});
for(propName in items[catName])
{
var option = $("<option />", {
text: items[catName][propName],
value: propName
});
optGroup.append(option);
}
$("#Cars").append(optGroup);
}

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);

Categories