How to Calculate Values of Options from Different Select - javascript

I am trying to calculate values of selected indexes. Dropdowns are dynamic so I might have 3 dropdowns, 5 dropdowns or 8 dropdowns. When I try to calculate values of selected indexes, I get NaN. Am I missing something?
function calculate() {
var calculationSpan = document.getElementById("calculationSpan");
var add;
var selects = document.querySelectorAll(".rooms");
selects.forEach(function (select) {
var roomsOfType = select.options[select.selectedIndex].value;
if (roomsOfType != 0) {
add = parseInt(add) + parseInt(select.options[select.selectedIndex].value);
}
});
calculationSpan.innerHTML = add;
}
<select class="rooms">
<option value="0">0</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select class="rooms">
<option value="0">0</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
<option value="6">Six</option>
</select>
<select class="rooms">
<option value="0">0</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>
<button onclick="calculate()">
Calculate
</button>
<span id="calculationSpan"></span>

Basically you need a start value for add.
var add = 0;
And you have to borrow Array#forEach, because selects is an array like object, but not an array.
You need Function#call for using selects as thisArg.
[].forEach.call(selects, function (/* ... */ ))
function calculate() {
var calculationSpan = document.getElementById("calculationSpan"),
add = 0,
selects = document.querySelectorAll(".rooms");
[].forEach.call(selects, function (select) {
var roomsOfType = +select.options[select.selectedIndex].value;
if (roomsOfType) {
add += roomsOfType;
}
});
calculationSpan.innerHTML = add;
}
<select class="rooms"><option value="0">0</option><option value="1">One</option><option value="2">Two</option><option value="3">Three</option></select>
<select class="rooms"><option value="0">0</option><option value="1">One</option><option value="2">Two</option><option value="3">Three</option><option value="4">Four</option><option value="5">Five</option><option value="6">Six</option></select>
<select class="rooms"><option value="0">0</option><option value="1">One</option><option value="2">Two</option><option value="3">Three</option><option value="4">Four</option></select>
<button onclick="calculate()">Calculate</button>
<span id="calculationSpan"></span>

Related

jQuery Store each value as a variable

I'm looping through each select with the class specialMenuCat and grabbing its value.
I'm using console.log() which shows the correct value but I'm not sure how to store this as a variable to use later.
<select class="specialMenuCat" name="menuCategory[]">
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="peach">Peach</option>
<option value="banana">Banana</option>
</select>
$('select.specialMenuCat').change(function(){
$('select.specialMenuCat').each(function(){
var catVal = $(this).val();
console.log(catVal);
});
});
An example of the console log is;
apples (5)
oranges (4)
peach (5)
banana (5)
I tried setting the vars first and then incrementing them but it didn't work. My attempt;
$('select.specialMenuCat').change(function(){
var apples = 0;
$('select.specialMenuCat').each(function(apples){
var catVal = $(this).val();
if(catVal == apples) { apples++; }
console.log(catVal);
});
});
initialize apple variable outside the onchange scope
because every time its re-initialize thats why value not increase
var apple = 0;
var apple = 0;
$('select.specialMenuCat').change(function() {
$('select.specialMenuCat').each(function() {
var catVal = $(this).val();
if (catVal == "apples") {
apple++;
}
console.log(catVal);
});
console.log(apple);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="specialMenuCat" name="menuCategory[]">
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="peach">Peach</option>
<option value="banana">Banana</option>
</select>
Declare an object and push value into it every change by increment in its occurrence
in result you can get the value by accessing the property name by example number of apples the should be like result['apple']
See belwon snippet :
$('select.specialMenuCat').change(function(){
$(".as-console").html("");
result = {};
$('select.specialMenuCat').each(function(){
if(!this.value) return;
val = result[this.value];
result[this.value] = typeof(val)== 'undefined' ? 1 : ++val;
});
console.log(result);
for (var prop in result) {
if (result.hasOwnProperty(prop)) {
console.log("number of "+ prop + " is: " + result[prop])
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="specialMenuCat" name="menuCategory[]">
<option value=""></option>
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="peach">Peach</option>
<option value="banana">Banana</option>
</select>
<select class="specialMenuCat" name="menuCategory[]">
<option value=""></option>
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="peach">Peach</option>
<option value="banana">Banana</option>
</select>
<select class="specialMenuCat" name="menuCategory[]">
<option value=""></option>
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="peach">Peach</option>
<option value="banana">Banana</option>
</select>
<select class="specialMenuCat" name="menuCategory[]">
<option value=""></option>
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="peach">Peach</option>
<option value="banana">Banana</option>
</select>
<select class="specialMenuCat" name="menuCategory[]">
<option value=""></option>
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>>
<option value="date">Dates</option>
</select>
<select class="specialMenuCat" name="menuCategory[]">
<option value=""></option>
<option value="melon">Melon</option>
<option value="oranges">Oranges</option>>
<option value="date">Dates</option>
</select>
the apples variable is inside your change function, so it won't exist outside your change function. This should work:
var apples = 0;
$('select.specialMenuCat').change(function(){
apples = 0; //reset, because you will start a new count
$('select.specialMenuCat').each(function(item){
var catVal = $(this).val();
if(catVal == "apples") { apples++; }
console.log(catVal);
});
});
function SomeOtherEvent(){
console.log(apples);
}
In the following Demo:
As suggested by Mr. McCrossan, create an Object Literal that has the fruit variables stored within. Keep your variables outside a function if you plan to increment/decrement the values. Referencing a value outside a function will create a closure which in turn causes a value to exist past the runtime of the function and thereby insuring a growing/shrinking value to build upon.
Register the select.fruit to the 'change' event
Get the value of the changed select with either this or event.target (in this Demo this is used).
Run the value through a switch() (I picked switch because it illustrates intentions very well).
On each matching case the value of the fruit property is incremented in the F Object as well as the corresponding output.
Demo
Details commented in Demo
/* Object literal stores each value
|| Note it is outside of a function
*/
var F = {
apples: 0,
oranges: 0,
peaches: 0,
bananas: 0
};
// Any change events that happen on a .fruit, callback runs
$('.fruit').on('change', fruitCount);
// This callback passes the Event Object (not used in this Demo)
function fruitCount(e) {
// "this" is the <select> currently changed
var currentPick = this.value;
switch (currentPick) {
/* if the value of "this" is "apples"...
|| increment the 'apples' property of the F Object
|| and then increment the value of output#A
|| But if it isn't apples fall onto the next case
*/ // Same applies to the other fruits
case 'apples':
F.apples++;
$('#A').val(F.apples);
break;
case 'oranges':
F.oranges++;
$('#O').val(F.oranges);
break;
case 'peaches':
F.peaches++;
$('#P').val(F.peaches);
break;
case 'bananas':
F.bananas++;
$('#B').val(F.bananas);
break;
default:
break;
}
}
select,
label,
output {
font: inherit;
}
label {
display: inline-block;
width: 8ch
}
<fieldset>
<legend>Fruit-O-Rama</legend>
<label>Apples: </label><output id='A'></output><br>
<label>Oranges: </label><output id='O'></output><br>
<label>Peaches: </label><output id='P'></output><br>
<label>Bananas: </label><output id='B'></output><br>
</fieldset>
<select class="fruit" name="menu0[]">
<option value=""></option>
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="peaches">Peaches</option>
<option value="bananas">Bananas</option>
</select>
<br>
<select class="fruit" name="menu1[]">
<option value=""></option>
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="peaches">Peaches</option>
<option value="bananas">Bananas</option>
</select>
<br>
<select class="fruit" name="menu2[]">
<option value=""></option>
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="peaches">Peaches</option>
<option value="bananas">Bananas</option>
</select>
<br>
<select class="fruit" name="menu3[]">
<option value=""></option>
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="peaches">Peaches</option>
<option value="bananas">Bananas</option>
</select>
<br>
<select class="fruit" name="menu4[]">
<option value=""></option>
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="peaches">Peaches</option>
<option value="bananas">Bananas</option>
</select>
<br>
<select class="fruit" name="menu5[]">
<option value=""></option>
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="peaches">Peaches</option>
<option value="bananas">Bananas</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Disable 3th, 4th dropdown list if 1st or 2nr are selected

I have this issue: In my form there are 4 dropdownlist and when the 1st (category1) or 2nd (software1) dropdown list is selected, the 3th (category2) and 4th (software2) must be disabled.
For this issue I find this script at disable-second-dropdown-if-the-first-is-not-selected but I do not trust to modify this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
category1
<select name='cat1'>
<option value='0'>Select one</option>
<option value='1'>little</option>
<option value='2'>good</option>
</select>
software1
<select name='soft1'>
<option value=''>Select one</option>
<option value='W'>Word</option>
<option value='E'>Excel</option>
<option value='PP'>Power Point</option>
</select>
<br />
category2
<select name='cat2'>
<option value='0'>Select one</option>
<option value='1'>little</option>
<option value='2'>good</option>
</select>
software2
<select name='soft2'>
<option value=''>Select one</option>
<option value='W'>Word</option>
<option value='E'>Excel</option>
<option value='PP'>Power Point</option>
</select>
<script type="text/javascript">
var setEnabled = function(e) {
var name = this.name.replace(/1/, '2'); //get name for second drop down
$('select[name=' + name + ']')
.prop('disabled', 0 === this.selectedIndex) // disable if selected option is first one
};
$(function() {
$('select[name=cat1], select[name=soft1]')
.on('change', setEnabled)
.trigger('change'); // trigger on page load
});
</script>
How to modify this?
Thanks
I think the main thing you want is to flip === for !==
However, to get this working on a matrix, where both top inputs trigger enabling/disabling of both bottom inputs, you'll need to test both on change of either.
var setEnabled = function(e) {
var selected = $('select[name=cat1]').prop('selectedIndex') > 0 || $('select[name=soft1]').prop('selectedIndex') > 0;
$('select[name=cat2], select[name=soft2]').prop('disabled', selected); // disable if selected option is first one
if (selected) {
$('select[name=cat2], select[name=soft2]').prop('selectedIndex', 0)
}
};
$(function() {
$('select[name=cat1], select[name=soft1]')
.on('change', setEnabled)
.trigger('change'); // trigger on page load
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</script>
category1
<select name='cat1'>
<option value='0'>Select one</option>
<option value='1'>little</option>
<option value='2'>good</option>
</select>
software1
<select name='soft1'>
<option value=''>Select one</option>
<option value='W'>Word</option>
<option value='E'>Excel</option>
<option value='PP'>Power Point</option>
</select>
<br />
category2
<select name='cat2'>
<option value='0'>Select one</option>
<option value='1'>little</option>
<option value='2'>good</option>
</select>
software2
<select name='soft2'>
<option value=''>Select one</option>
<option value='W'>Word</option>
<option value='E'>Excel</option>
<option value='PP'>Power Point</option>
</select>

javascript - get selected value from select list

i got a form with a select form elements for month.
<select id="month" name="month">
<option value="Jan">Jan</option>
<option value="Feb">Feb</option>
<option>Mar
<option>Apr
<option>May
<option>Jun
<option>Jul
<option>Aug
<option>Sept
<option>Oct
<option>Nov
<option>Dec
</select>
How do i use javascript to get compare the selected value. for example if i select Feb, the javascript will pop up "you selected feb"
var monthSelect = document.getElementById("month")
var opt = monthSelect.options[monthSelect.selectedIndex]
if(opt.text == "Feb")
{
alert("Feb selected")
return false
}
JSFiddle: https://jsfiddle.net/ebrnh047/
Your html:
<select id="month">
<option value="Jan">Jan</option>
<option value="Feb">Feb</option>
</select>
Try:
var month = document.getElementById("month");
month.onchange = function() {
if (month.value == "Feb") {
alert("Feb selected");
}
}
This is a way to do it with JavaScript only:
First, your HTML:
<select id="month" name="month">
<option value="Jan">Jan</option>
<option value="Feb">Feb</option>
<option value="Mar">Mar</option>
<option value="Apr">Apr</option>
<option value="May">May</option>
<option value="Jun">Jun</option>
<option value="Jul">Jul</option>
<option value="Aug">Aug</option>
<option value="Sep">Sep</option>
<option value="Oct">Oct</option>
<option value="Nov">Nov</option>
<option value="Dec">Dec</option>
</select>
Then, your script:
var monthSelect = document.getElementById("month");
monthSelect.onchange = function(){
var thisValue = this.value;
alert(thisValue);
};
This is the fiddle: https://jsfiddle.net/16sn90tp/
Make sure you execute this code on document ready event( window.onload )
var monthSelect = document.getElementById("month")
monthSelect.onchange = function() {
var opt = monthSelect.options[monthSelect.selectedIndex]
if (opt.text == "Feb") {
alert("Feb selected")
}
}
<select id="month" name="month">
<option value="Jan">Jan</option>
<option value="Feb">Feb</option>
<option>Mar
<option>Apr
<option>May
<option>Jun
<option>Jul
<option>Aug
<option>Sept
<option>Oct
<option>Nov
<option>Dec
</select>
Jan Feb
function myFunction() {
var monthSelect = document.getElementById("month").value;
if (monthSelect == "Feb") {
alert("Feb selected");
return false;
}
}
<select id="month" name="month" onchange="myFunction()">
<option value="Jan">Jan</option>
<option value="Feb">Feb</option>
</select>
Hi add at first a class called "month" to all of your option tags and one class "monthList" to the select like for example this:
<select class="monthList">
<option class="month">Jan</option>
<option class="month">Feb</option>
<option class="month">Mar</option>
...
</select>
After this you need a little bit of JQuery:
$(".monthList .month").click(function(){
var selectedMonth = $(this).text();
var showText = "you selected " + selectedMonth;
alert(showText);
});
Try this, it should work.

Two HTML selects with differing selected values

I got following HTML code:
<select id="first">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="second">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
So both of them have same data. I need to secure, that user can't select same value in both of them.
I hoped, that JQuery has some nice feature like:
$("#first").getOptions()
or even
$("#first").setOptions()
but unfortunately, it doesn't. This makes it very complicated for me, because I don't know JQuery very well ...
So, what is the best approach to solve my problem?
You can get the value of the currently selected option by doing:
$('#first option:selected').text();
$('#second option:selected').text();
Assuming I understand your question, you don't want the user to be able to enter the same value in each box. So, something similar to:
$first = $('#first');
$second = $('#second');
$first.on('change', function() {
$second.find('option').attr('disabled', false);
var firstVal = $first.find('option:selected').text();
$second.find('option:contains("'+ firstVal +'")').attr('disabled', true);
});
$second.on('change', function() {
$first.find('option').attr('disabled', false);
var secondVal = $second.find('option:selected').text();
$first.find('option:contains("'+ secondVal +'")').attr('disabled', true);
});
I should probably note that there are ways for you to achieve your getOptions() and setOptions() ideas, you can do $select.find('option') to get the options. For setting them, define some options in html and set the select element's innerHTML to those elements:
var options = '<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>';
$select.html(options);
JSFiddle demo
You can disable single options in your select
<select id="second">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2" disabled>Two</option>
<option value="3">Three</option>
</select>
Handle event onSelect on first select and based on it disable proper <option> in second select
When one is changed, if the other is the same, you could change it back to default, like this.
$(document).on('change', '#first', function() {
var firstVal = $('#first').val();
var secondVal = $('#second').val();
if (firstVal == secondVal) {
$('#second').val(0);
}
});
$(document).on('change', '#second', function() {
var firstVal = $('#first').val();
var secondVal = $('#second').val();
if (firstVal == secondVal) {
$('#first').val(0);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="first">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="second">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Try this(codepen):
HTML:
<select id="first">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="second">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Javascript/jQuery:
var strUser;
var strUser2;
$(function() {
$("#first").change(function() {
var e = document.getElementById("first");
strUser = e.options[e.selectedIndex].text;
if (strUser == strUser2) {
alert("Dropdowns contain the same value. Change one.")
document.getElementById("first").disabled=true;
} else {
document.getElementById("second").disabled=false;
}
});
});
$(function() {
$("#second").change(function() {
var e = document.getElementById("second");
strUser2 = e.options[e.selectedIndex].text;
if (strUser2 == strUser) {
alert("Dropdowns contain the same value. Change one.")
document.getElementById("second").disabled=true;
} else {
document.getElementById("first").disabled=false;
}
});
});
Essentially, this code will retrieve selected values from the dropdowns on change, and then a comparison will be made. If the values are equal, the recently selected dropdown will be disabled. You then will have to select a different value in the other dropdown to re-enable the disabled dropdown. Here's the codepen that displays the working functionality. This will not allow a user to select two of the same values without a dropdown being disable and turned off.

jQuery remove SELECT options based on another SELECT selected (Need support for all browsers)

Say I have this dropdown:
<select id="theOptions1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
I want it so that when the user selects 1, this is the thing that the user can choose for dropdown 2:
<select id="theOptions2">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
Or if the user selects 2:
<select id="theOptions2">
<option value="a">a</option>
<option value="b">b</option>
</select>
Or if the user selects 3:
<select id="theOptions2">
<option value="b">b</option>
<option value="c">c</option>
</select>
I tried the code posted here:
jQuery disable SELECT options based on Radio selected (Need support for all browsers)
But it doesn't work for selects.
Please help!
Thank you!
UPDATE:
I really like the answer Paolo Bergantino had on:
jQuery disable SELECT options based on Radio selected (Need support for all browsers)
Is there anyway to modify this to work with selects instead of radio buttons?
jQuery.fn.filterOn = function(radio, values) {
return this.each(function() {
var select = this;
var options = [];
$(select).find('option').each(function() {
options.push({value: $(this).val(), text: $(this).text()});
});
$(select).data('options', options);
$(radio).click(function() {
var options = $(select).empty().data('options');
var haystack = values[$(this).attr('id')];
$.each(options, function(i) {
var option = options[i];
if($.inArray(option.value, haystack) !== -1) {
$(select).append(
$('<option>').text(option.text).val(option.value)
);
}
});
});
});
};
This works (tested in Safari 4.0.1, FF 3.0.13):
$(document).ready(function() {
//copy the second select, so we can easily reset it
var selectClone = $('#theOptions2').clone();
$('#theOptions1').change(function() {
var val = parseInt($(this).val());
//reset the second select on each change
$('#theOptions2').html(selectClone.html())
switch(val) {
//if 2 is selected remove C
case 2 : $('#theOptions2').find('option:contains(c)').remove();break;
//if 3 is selected remove A
case 3 : $('#theOptions2').find('option:contains(a)').remove();break;
}
});
});
And the beautiful UI:
<select id="theOptions1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br />
<select id="theOptions2">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
You can add classes to your <option>s to store which go with each value of #theOptions1:
<select id="theOptions2">
<option value="a" class="option-1 option-2">a</option>
<option value="b" class="option-1 option-2 option-3">b</option>
<option value="c" class="option-1 option-3">c</option>
</select>
then do this:
$(function() {
var allOptions = $('#theOptions2 option').clone();
$('#theOptions1').change(function() {
var val = $(this).val();
$('#theOptions2').html(allOptions.filter('.option-' + val));
});
});
For the record you can NOT remove options in a select list in Internet Explorer.
try this. this will definitely work
$(document).ready(function () {
var oldValue;
var oldText;
var className = '.ddl';
$(className)
.focus(function () {
oldValue = this.value;
oldText = $(this).find('option:selected').text();
})
.change(function () {
var newSelectedValue = $(this).val();
if (newSelectedValue != "") {
$('.ddl').not(this).find('option[value="' + newSelectedValue + '"]').remove();
}
if ($(className).not(this).find('option[value="' + oldValue + '"]').length == 0) { // NOT EXIST
$(className).not(this).append('<option value=' + oldValue + '>' + oldText + '</option>');
}
$(this).blur();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form action="/Home/Ex2" method="post">
<select class="ddl" id="A1" name="A1">
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<hr />
<select class="ddl" id="A2" name="A2">
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<hr />
<select class="ddl" id="A3" name="A3">
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<hr />
<select class="ddl" id="A4" name="A4">
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<hr />
<input type="submit" name="submit" value="Save Data" id="btnSubmit" />
</form>
Actually, using the code below will remove a dropdown option just fine in IE, as long as it is not the selected option (it will not work on "a" without deselecting that option first):
var dropDownField = $('#theOptions2');
dropDownField.children('option:contains("b")').remove();
You just run this to remove whatever option you want to remove under a conditional statement with the first group (theOptions1) - that if one of those is selected, you run these lines:
var dropDownField = $('#theOptions2');
if ($('#theOptions1').val() == "2") {
dropDownField.children('option:contains("c")').remove();
}
if ($('#theOptions1').val() == "3") {
$("#theOptions2 :selected").removeAttr("selected");
$('#theOptions2').val('b');
dropDownField.children('option:contains("a")').remove();
}
-Tom

Categories

Resources