Fill multiple select boxes with JSON data - javascript

I have got the following database table (there is more data in the database though, this is not all!):
catid value description
0 350 350 euro
0 500 500 euro
0 650 650 euro
1 0 No
1 1 Yes
With the help of PHP and json_encode() i'm creating a JSON string of this table:
jQuery171024539993586950004_1349776890005([{"0":"0","catid":"0","1":"350","value":"350","2":"350 euro","description":"350 euro"},{"0":"0","catid":"0","1":"500","value":"500","2":"500 euro","description":"500 euro"},{"0":"0","catid":"0","1":"650","value":"650","2":"650 euro","description":"650 euro"},{"0":"1","catid":"1","1":"0","value":"0","2":"No","description":"No"},{"0":"1","catid":"1","1":"1","value":"1","2":"Yes","description":"Yes"}])
Now what i want is to use the JSON to fill select boxes, just like you would in HTML:
<select id="0">
<option value="350">350 euro</option>
<option value="500">500 euro</option>
<option value="650">650 euro</option>
</select>
<select id="1">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
Can anyone help me with this? I know how to do a loop to fill a table (with $.getJSON), but i'm kinda stuck with this one.

This function will loop through your posted object and populate the menus (given your posted source):
var populateSelects = function(data) {
var cat0 = $('select#0'),
cat1 = $('select#1'),
opt = $('<option />'),
newOpt = {},
cat0opts = [],
cat1opts = [];
$.each(data, function(i, obj) {
//clone the option element so as to not re-create a new one
newOpt = opt.clone();
//obj is the JavaScript object in the array, so
//dot-notation works nicely
newOpt.text(obj.description).val(obj.value);
if (obj.catid === "0") {
//push the DOM element, not the jQuery object
cat0opts.push(newOpt[0]);
} else if (obj.catid === "1") {
cat1opts.push(newOpt[0]);
}
});
//Add the array of DOM elements to their respective menus,
//clearing out any existing menu items.
cat0.empty().append(cat0opts);
cat1.empty().append(cat1opts);
};
Here's a fiddle of it in action: http://jsfiddle.net/a5MTE/1/
One note of importance is the catid comparison... if the parsed JSON returns catid as number (not a string) you'll want to change the comparison to if (obj.catid === 0).

by the json parsing you should have to make a parser and by if and else condition on addcat you will be able to do it

Related

Set value on select options to select JSON data

I'm creating a select based on the JSON I got with an API. Based on that select, when I choose another option I want some data to change (text and image src).
I got the select with the options done. Each option is a name and I done that with forEach. My problem is setting the value so I can use it to change the other data. In my mind the easiest solution would be setting the value to the objects index so when I choose the first option I get 0 and can get the first JSON object. I'm not sure if this is the best way anyway.
This is my code reduced to only the forEach:
<select name="select" id="selector"> </select>
data_json.show.forEach((element) => {
document.getElementById('selector').innerHTML +=
`<option value="">${element.name}</option>`;
});
(the value is what I want to be the same as the index of each json data)
My idea of what I want to get:
<select name="select" id="selector">
<option value="0">Name_01</option>
<option value="1">Name_02</option>
<option value="2">Name_03</option>
</select>
So I can use the value like this:
let titulos = document.getElementById("titulos");
selectVal.onchange = function() {
let actualVal = selectVal.options[selectVal.selectedIndex].value;
titulos.innerHTML = "Títulos:" + " " + data_json.show[actualVal].image;;
};
<p id="titulos">Títulos:</p>
Hope it makes sense
You're setting them all to an empty value. You can use the array index to give them each a different value.
data_json.show.forEach((element, index) => {
document.getElementById('selector').innerHTML +=
`<option value="${index+1}">${element.name}</option>`;
});
BTW, you can simplify selectVal.options[selectVal.selectedIndex].value to just selectVal.value.

Count total value of selected options using javascript

i've tried to count the value of selected option of the following multiple combo box.
<form method="post" name="transaksi" action="proc.php">
<select name="bulan_catering[]" id="id_cur_month_catering" size="12" multiple="multiple" onchange="update_catering()">
<option value="jul-20132014-3500">[2013-2014] July</option>
<option value="aug-20132014-3700">[2013-2014] August </option>
<option value="sep-20132014-4100">[2013-2014] September </option>
<option value="oct-20132014-4200">[2013-2014] October </option>
<option value="nov-20132014-4800">[2013-2014] November </option>
<option value="dec-20132014-5100">[2013-2014] December </option>
</select>
Total payment: <input type="text" name="catering">
And i use this simple javascript to get the value.
<script type="text/javascript" language="javascript">
function update_catering() {
var num_month_catering = document.getElementBy("id_cur_month_catering").value;
var cur_payment_catering = num_month_catering.substring(13);
document.transaksi.catering.value = cur_payment_catering;
}
</script>
What i need to do is, for example if user selects july, august and september, it should count 3500+3700+4100. and the result for total payment should 11300. But it doesn't work as i want. It is only showing value of the last selected option. in this case it shows 4100 (last value). Can some one help me to do the right way in javascript as i explained above, please.
Thank You.
This is a fairly basic solution. You should do research before posting a question on StackOverflow. But here's your solution
var intNumber = 0;
var arrListOptions = document.getElementById('id_cur_month_catering').options;
for(intIterator = 0; intIterator < arrListOptions.length; intIterator ++){
if (arrListOptions[intIterator].selected == true){
intNumber += parseInt(arrListOptions[intIterator].value.split('-')[2]);
}
}
intNumber would contain the sum of each number selected in the list.
Here's the list of link that would allow you to learn the basis on javascript for this short script:
http://www.w3schools.com/js/js_loop_for.asp
http://www.w3schools.com/jsref/coll_select_options.asp
http://www.w3schools.com/jsref/jsref_parseint.asp
Also, here's an example of a similar question you could have inspired yourself from:
Javascript Get Values from Multiple Select Option Box
I would also recommand you to learn jQuery as this would allow you to have access to more coding functionnality that are relatively common nowday (like foreach in php, would be .each in jQuery).
That would help you be more prepared later when doing development.
I hope this have been helpful :-)
The cool thing is that jQuery .val() method returns an array of values for select box with multiple attribute, so, just go through that array and collect the prices ( with .replace() and regex for example ), and calculate the sum of values with .reduce().
$( '#id_cur_month_catering' ).on( 'change', function() {
var sum = $(this).val()
.map( function( value ) {
return value.replace( /.+?-(\d+)$/, function( match, num ) { return num; });
})
.reduce( function(a, b) {
return parseInt(a, 10) + parseInt(b, 10);
});
$( 'input[name=catering]' ).val( sum );
})
However, I'm not sure whether is jQuery relevant for this question.
FIDDLE
I'd personally suggest:
function update_catering() {
// getting all the options, and turning them into an Array (from a NodeList),
// iterating over that array to keep only those that are selected:
var selectedOptions = [].slice.call(this.options, 0).filter(function(opt) {
return opt.selected;
}),
// iterating over the selectedOptions array to form a map of the values:
values = selectedOptions.map(function(opt) {
// keeping the numeric last-numbers from the value of the option element:
return parseFloat((/\d+$/).exec(opt.value));
});
// setting the value of the <input> element to the sum of the selected
// <option> elements' numbers:
document.getElementById('result').value = values.reduce(function(a, b) {
return a + b;
});
}
// binding the change event-handler outside of the HTML, for a less
// obtrusive approach:
document.getElementById('id_cur_month_catering').addEventListener('change', update_catering, false);
<form method="post" name="transaksi" action="proc.php">
<select name="bulan_catering[]" id="id_cur_month_catering" size="12" multiple="multiple">
<option value="jul-20132014-3500">[2013-2014] July</option>
<option value="aug-20132014-3700">[2013-2014] August</option>
<option value="sep-20132014-4100">[2013-2014] September</option>
<option value="oct-20132014-4200">[2013-2014] October</option>
<option value="nov-20132014-4800">[2013-2014] November</option>
<option value="dec-20132014-5100">[2013-2014] December</option>
</select>
Total payment:
<input id="result" type="text" name="catering">
</form>
References:
Array.prototype.filter().
Array.prototype.forEach().
Array.prototype.map().
Array.prototype.slice().

<select> tag and returning multiple values to javascript method

I have an issue with the data which is sent from a drop down menu, the selector only returns a single value, even when multiple values are selected. I have searched online for a solution to this, but they all use PHP, JQuery or some method outside the scope of the course I am taking; to capture multiple selected items. I have tried .value of the individual options, but that returns all of the options rather than just the ones which are selected. Is there some kind of trick to sending multiple values?
Here is my code for the menu. For example If I select JAVA PROGRAMMING, NETWORKS and VIDEO GAMES, only JAVA PROGRAMMING is sent.
<select multiple id="CK_Expertise">
<option id="CK_Exp1" value="Java programming">JAVA PROGRAMMING</option>
<option id="CK_Exp2" value="Networks">NETWORKS</option>
<option id="CK_Exp3" value="Video game programming">VIDEO GAMES</option>
<option id="CK_Exp4" value="Accounter">ACCOUNTER</option>
<option id="CK_Exp5" value="Help Desk">HELPDESK</option>
<option id="CK_Exp6" value="C++ programming">C++</option>
<option id="CK_Exp7" value="Programming">PROGRAMMING</option>
</select>
I have also tried using the Select Object in the DOM, http://www.w3schools.com/jsref/dom_obj_select.asp
which has a few methods for accessing the options in the dropdown menu. One method in particular called selectedIndex, seemed to be what I am looking for, however it only returns the the index of the first selected option, instead of all of the selected options.
Is there a simple solution to this using just Javascript and the DOM?
Thanks
- Chris
Get the options, iterate and check if they are selected, and add the values to an array
var select = document.getElementById('CK_Expertise'),
options = select.getElementsByTagName('option'),
values = [];
for (var i=options.length; i--;) {
if (options[i].selected) values.push(options[i].value)
}
console.log(values)
FIDDLE
or being a little more fancy
var select = document.getElementById('CK_Expertise'),
values = Array.prototype.filter.call(select.options, function(el) {
return el.selected;
}).map(function(el) {
return el.value;
});
console.log(values)
FIDDLE
You could use the select.selectedOptions property:
select.onchange = function() {
var values = [].map.call(this.selectedOptions, function(opt){
return opt.value;
});
};
document.getElementById('CK_Expertise').onchange = function() {
document.querySelector('pre').textContent = JSON.stringify([].map.call(
this.selectedOptions, function(opt){ return opt.value; }
));
}
<select multiple id="CK_Expertise">
<option id="CK_Exp1" value="Java programming">JAVA PROGRAMMING</option>
<option id="CK_Exp2" value="Networks">NETWORKS</option>
<option id="CK_Exp3" value="Video game programming">VIDEO GAMES</option>
<option id="CK_Exp4" value="Accounter">ACCOUNTER</option>
<option id="CK_Exp5" value="Help Desk">HELPDESK</option>
<option id="CK_Exp6" value="C++ programming">C++</option>
<option id="CK_Exp7" value="Programming">PROGRAMMING</option>
</select>
<pre></pre>
If you can use jQuery, this will give you all the values
$(document).ready(function(){
$('#CK_Expertise').change(function(e){
var values = $('#CK_Expertise').val()
alert(values);
});
});
HTH,
-Ted
You could iterate storing select.selectedIndex in an array and unselecting the corresponding option to get the next one:
select.onchange = function() {
var i, indices=[], values = [];
while((i=this.selectedIndex) > -1) {
indices.push(i);
values.push(this.value);
this.options[i].selected = false;
}
while((i=indices.pop()) > -1)
this.options[i].selected = true;
console.log(values);
}
Demo
This way you avoid iterating over all options, but you must iterate twice over the selected ones (first to unselect them, them to select them again).
Why not using an indexed variable in the SELECT command?
<SELECT MULTIPLE id="stuff" name="stuff[]">
<OPTION value=1>First stuff</option>
<OPTION value=2>Second stuff</option>
<OPTION value=3>Third stuff</option>
</SELECT>
In that case it's easy to read the array:
$out=$_REQUEST['stuff'];
foreach($out AS $thing) {
echo '<br />'.$thing;
}
Sorry for the poor indentation, but I just wanted to show the way I use for solving this case!
var select = document.getElementById('CK_Expertise'),
options = select.selectedOptions,
values = [];
for(let i=0;i<options.length;i++)
{
values.push(options[i].value);
}
console.log(values);

jQuery Dropdown List Contains Filter

I have two dropdown lists that filter content. The first one is the locations and the second one is the jobs. The first list filters the second. I'm using a :contains to read the string values that allow my filter to work. I'm running into a problem when I want to use two contains at once as a filter. Here is the code:
HTML
<div class="holder">
<label for="volunteerLocation">Where do you want to volunteer?</label><br>
<select id="locations">
<option value="0">--Select a Campus--</option>
<option value="5">Location 1</option>
<option value="6">Location 2</option>
<option value="7">Location 3</option>
</select>
</div>
<br />
<div class="holder">
<label for="volunteerJobs">In which area would you like to serve?</label><br />
<select id="jobs">
<option value="1">Job 1 (Location 1)</option>
<option value="2">Job 2 (Location 2)</option>
<option value="3">Job 3 (Location 3)</option>
<option value="4">Job 4 (All locations)</option>
</select>
</div>
Javascript
var select = $('#jobs');
var options = [];
$(select).find('option').each(function () {
options.push({ value: $(this).val(), text: $(this).text() });
});
$(select).data('options', options);
$('#locations').change(function () {
filterText = $("#locations option:selected").text();
var optionList = $(select).empty().data('options');
var j = 0;
$.each(optionList, function (i) {
var option = options[i];
if (option.text.indexOf(filterText) !== -1) {
if (j == 0) {
$('#jobs').prepend("<option value=''>--Select a Job--</option>").val('');
j++;
};
$(select).append(
$('<option>').text(option.text).val(option.value)
);
}
if (filterText == "--Select a Campus--") {
$(select).append(
$('<option>').text(option.text).val(option.value)
);
}
})
})
Here is a JSLint of this so you can see it in action Full Example
I'm trying to get "Job 4" to show up on everything but the "Select a Campus" option. How do I do that?
instead of looping with .each every time location change, and going through exceptions, me would create an index upon page load
var locJobs=new Array();
then you fill it with your data, for example
locJobs['5']=new Array();
locJobs['5'] = ['job 1','job 2']
then on change
$("#jobs").html('<option>'+locJobs[$(this).val()].join('</option><option>')+'</option>');
if you need to add the value on the options of #jobs you'll have to complicate that snippet a bit.
It shall be more efficient & also make maintenance much easier (no exceptions to deal with just an array to populate from whatever data source you are using) as you'll end up with a very flexible solution
nb: you declare var select = $("#jobs") but then you use $(select); that is a useless overhead use select directly
a convention to keep code clear is to add $ to any variable that is caching a jquery object :
var $select=$("#select")
then you use $select.whtever(//...

Obtain the number of the item in an options menu?

I'm using .val() in jQuery to retain the value of an options menu onChange.
How would I retain the number (as in as it is ordered) of the item in the drop down using jQuery?
<select>
<option> //option 1
<option> //option 2
</select>
Here is what I have set up now:
<select id="start_month" onChange="getMonthDay()">
<option>Jan</option>
<option>Feb</option>
<option>March</option>
<option>April</option>
<select>
Using,
function getMonthDay()
{
$('#start_month').val()
}
I can get whatever value is selected, but my question is how do I get the Number down of this value in the markup? For March, I would want 3.. and so on
Can you reformulate your question better? I'm still lost in what do you want.
But, nevertheless here is how <select> works in jQuery
<select id="selection">
<option value="val_1">value 1</option>
<option value="val_2">value 2</option>
</select>
$("#selection").val() will give you val_1 or val_2 depending on witch item is currently selected.
If you want to go through all options and check the selected on, you can use
$("#selection option:selected").val();
or itenerate through all <option>'s
$("#selection option").each(function() {
if( $(this).is(":selected") ) {
var v = $(this).val();
}
});
If you want to retain all options you can easily clone them or assign them as data, if you want to keep those values throughout the pages, use Local Database or Cookies to persist the data.
To answer your question after your update:
First: Why don't you have:
<select id="start_month" onChange="getMonthDay()">
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">March</option>
<option value="4">April</option>
<select>
And use the value of the selected item?
Second: Just use what I wrote above and itenerate through the options
$("#start_month option").each(function(index, element) {
if( $(this).is(":selected") ) {
// get index position, remember to add 1 as arrays start at 0
var n = index;
// break each
return false;
}
});
You'd get a list of the <option> elements, find the selected one, and use index:
var $opts = $('#start_month option');
var zero_based_index = $opts.index($opts.filter(':selected'));
Demo: http://jsfiddle.net/ambiguous/HyukW/
Just add 1 if you want a one-based index.
I made something like this,with zero based key ;
<select id='deneme'>
<option>Val1</option>
<option>Val2</option>
<option>Val3</option>
<option>Val4</option>
</select>
$('#deneme').change(function(){
$.each( $('#deneme').children('option'),function(key,value){
if($(this).is(':selected'))
alert(key)
})
})
u can check from here http://jsfiddle.net/8JZCw/
No need for any iteration here, let jQuery do that for you, just get the selected index and increment...
$('#start_month option:selected').index() + 1

Categories

Resources