Count total value of selected options using javascript - 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().

Related

<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

javascript function not getting dropdown text

i am using javascript to get the text of selected item from dropdown list.
but i am not getting the text.
i am traversing the dropdown list by name..
my html dropdownlist is as:
<select name="SomeName" onchange="div1();">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
and my javascript is as:
function div1() {
var select = document.getElementsByName("SomeName");
var result = select.options[select.selectedIndex].text;
alert(result);
}
can you please help me out..
Option 1 - If you're just looking for the value of the selected item, pass it.
<select name="SomeName" onchange="div1(this.value);">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1(val)
{
alert(val);
}
Option 2 - You could also use the ID as suggested.
<select id="someID" name="SomeName" onchange="div1();">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1()
{
var ddl = document.getElementById("someID");
var selectedText = ddl.options[ddl.selectedIndex].value;
alert(selectedText);
}
Option 3 - You could also pass the object itself...
<select name="SomeName" onchange="div1(this);">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1(obj)
{
alert(obj.options[obj.selectedIndex].value);
}
getElementsByName returns an array of items, so you'd need:
var select = document.getElementsByName("SomeName");
var text = select[0].options[select[0].selectedIndex].text;
alert(text);
Or something along those lines.
Edit: instead of the "[0]" bit of code, you probably want either (a) to loop all items in the "select" if you expect many selects with that name, or (b) give the select an id and use document.getElementById() which returns just 1 item.
The problem with the original snippet posted is that document.getElementsByName() returns an array and not a single element.
To fix the original snippet, instead of:
document.getElementsByName("SomeName"); // returns an array
try:
document.getElementsByName("SomeName")[0]; // returns first element in array
EDIT: While that will get you up and running, please note the other great alternative answers here that avoid getElementsByName().

How to modify an HTML Select when the name is an array using Javascript

I have two html select objects named with the same name (they are arrays with different indexes).
What I am trying to do, is if "off" is selected from the category[0] select element, I would like to disable the category[1] element. I have been trying to use document.getElementsByName() but am having no luck figuring out how to specifically target the category[1] array. See below for example code.
<select name='category[0]'>
<option value='0'>off</option>
<option value='1'>on</option>
</select>
<select name='category[1]'></select>
My question is how can I modify the properties of an HTML object that is an array? I understand I could do this easily using ID's but I would like to learn how to do this using an array.
Thanks
Untested:
<select name='category[0]'>
<option value='0'>off</option>
<option value='1'>on</option>
</select>
<select name='category[1]'></select>
<script>
var selects = document.getElementsByTagName('select');
for ( var i = 0, len = selects.length; i<l; ++i ) {
if ( selects[i].name == 'category[1]' ) {
// operate on selects[i];
// you can also rely on getAttribute('name')
}
}
</script>
<select name='category[0]' onChange="disCat(this.value);">
<option value='0'>off</option>
<option value='1'>on</option>
</select>
<script type="text/javascript">
function disCat(val){
if(val!="0") return;
var sels=document.getElementsByTagName("select");
for(i=0;i<sels.length;i++)
{
if(sels[i].getAttribute('name')=='category[1]') sels[i].disabled=true;
}
}
</script>

Categories

Resources