I'm trying to limit the number of options based on another selection. For instance in this example "How many credits is the class you skipped?" should be limited to equal or less than the previous question "How many total credits are you taking this semester?". So if I'm only taking 9 credits on semester the second question of how many credits I'm skipping should be equal or less than the 9 credits for the whole semester.
Any help will be greatly appreciated.
Here is the jsfiddle: http://jsfiddle.net/k7tDP/1/
Here is the JS:
function calculateCost() {
'use strict';
// enter annual tuition
var $annualTuition = parseInt($('#annual_tuition').val());
// tuition per semester
var semesterTuition = Math.round($annualTuition / 3);
// total number of credits for semester
var $semesterCredits = parseInt($('#semester_credits').val());
// cost of a single credit
var singleCreditCost = semesterTuition / $semesterCredits;
// total credits for class being skipped
var $skippedTotalCredits = parseInt($('#skipped_total_credits').val());
// total cost for class being skipped
var skippedTotalCreditsCost = $skippedTotalCredits * singleCreditCost;
// number of times skipped class meets per week
var $skippedWeekDays = parseInt($('#skipping_class_meet').val());
// from date
var fromDate = $('#from').datepicker('getDate');
// to date
var toDate = $('#to').datepicker('getDate');
// calculate number of weeks in date range (semester) using 'from / to' dates
var skippedWeeks = Math.ceil((toDate - fromDate) / (1000 * 7 * 60 * 60 * 24));
console.log(skippedWeeks);
// total number of days in semester for class being skipped
//var $skippedTotalDays = parseInt($('#skipped_total_days').val());
var skippedTotalDays = $skippedWeekDays * skippedWeeks;
// (total cost of class) / (total number of class days in semester) = cost of class
var skippedSingleClassCost = skippedTotalCreditsCost / skippedTotalDays;
return skippedSingleClassCost.toFixed(2);
}
$(function() {
'use strict';
$('#from').datepicker({
defaultDate: '+1w',
changeMonth: true,
numberOfMonths: 1,
onSelect: function() {
//toDate = $(this).datepicker('getDate');
}
});
$('#to').datepicker({
defaultDate: '+1w',
changeMonth: true,
numberOfMonths: 1,
onSelect: function() {
//fromDate = $(this).datepicker('getDate');
}
});
$('#cost').on('click', function() {
$('.costFigure').fadeIn('fast');
$('#costTotal').html(calculateCost());
});
});
Here is the html:
<form id="costForm" action="#" onsubmit="#">
<div>
<label for="annual_tuition">What is your annual tuition (estimated)?</label>
<div class="styled_select">
<select name="annual_tuition" id="annual_tuition" value="tuition amount" autofocus>
<option value="0"> </option>
<option value="5000">$5,000</option>
<option value="10000">$10,000</option>
<option value="15000">$15,000</option>
<option value="20000">$20,000</option>
<option value="25000">$25,000</option>
<option value="30000">$30,000</option>
<option value="35000">$35,000</option>
<option value="40000">$40,000</option>
<option value="45000">$45,000</option>
<option value="50000">$50,000</option>
</select>
</div>
</div>
<div>
<label for="semester_credits">How many total credits are you taking this semester?</label>
<div class="styled_select">
<select name="semester_credits" id="semester_credits" value="" tabindex="2">
<option value="0"> </option>
<option value="3">3 credits</option>
<option value="6">6 credits</option>
<option value="9">9 credits</option>
<option value="12">12 credits</option>
<option value="13">13 credits</option>
<option value="14">14 credits</option>
<option value="15">15 credits</option>
<option value="16">16 credits</option>
<option value="17">17 credits</option>
<option value="18">18 credits</option>
</select>
</div>
</div>
<div>
<label for="skipped_total_credits">How many credits is the class you skipped?</label>
<div class="styled_select">
<select name="skipped_total_credits" id="skipped_total_credits" value="" tabindex="2">
<option value="0"> </option>
<option value="3">3 credits</option>
<option value="6">6 credits</option>
<option value="9">9 credits</option>
<option value="12">12 credits</option>
<option value="13">13 credits</option>
<option value="14">14 credits</option>
<option value="15">15 credits</option>
<option value="16">16 credits</option>
<option value="17">17 credits</option>
<option value="18" disabled>18 credits</option>
</select>
</div>
</div>
<div>
<label for="skipping_class_meet">How many times a week does the class you skipped meet?</label>
<div class="styled_select">
<select name="skipping_class_meet" id="skipping_class_meet" value="" tabindex="2">
<option value="0"> </option>
<option value="1">1 time a week</option>
<option value="2">2 times a week</option>
<option value="3">3 times a week</option>
<option value="4">4 times a week</option>
<option value="5">5 times a week</option>
</select>
</div>
</div>
<div class="dateRange clearfix">
<label>Between what months are you enrolled in this class?</label>
<div style="width: 48%; float: left;">
<label for="from">From:</label>
<input type="text" id="from" name="from">
</div>
<div style="width: 48%; float: right;">
<label for="to">To:</label>
<input type="text" id="to" name="to">
</div>
</div>
<div>
<button id="cost" type="button">Calculate</button>
</div>
<div class="costFigure">
<h1>your missed class cost you $<span id="costTotal"></span></h1>
</div>
</form>
On change of your dropdown fire a onchange trigger and on the basis of values make the 2nd dropdown enable or disabled.
$("#semester_credits").change(function () {
var $this=this;
$("#skipped_total_credits").children().each(function(){
$(this).attr("disabled",parseInt($this.value) < parseInt(this.value));
});
});
Check the fiddle here
EDIT
$this.value contains the value selected from "semester_credits" dropdown, now For each child of "skipped_total_credits", I am checking if that value is less than the children value then make it disabled, i.e attr("disabled", true) else make that children enabled.
I've created a quick function to help you out, there may be a neater way to do this, but it does the job quite nicely!
Onchange of the element #semester_credits I grab the value (number of semesters credits and then loop over the next select box and remove the ones that have a higher value that the chosen one, I use a global var to cache the removed options in case the user changes their minds and we need to add them back in.
$(function () {
var savedOpts = "";
$('#semester_credits').change(function() {
//Add all options back in;
if( savedOpts ) {
$('#skipped_total_credits').append(savedOpts);
savedOpts = "";
}
//Return false if blank option chosen;
if( $(this).val() === "0" )
return false;
var chosenCreds = parseInt($(this).val());
$('#skipped_total_credits option').each(function() {
var thisCred = parseInt($(this).val());
if(thisCred > chosenCreds) {
//Remove
savedOpts += $(this)[0].outerHTML;
$(this).remove();
}
});
});
Here an updated fiddle
p.s the example Kai Hartmann suggests is also a nice way to achieve this.
If you want the drop-down list for a question to change based on previous answer, you need to add an onchange event to each select element which would update another drop-down. This should then call a function which removes or adds elements in your form.
Otherwise, you can add a validation function for your Calculate button.
Related
So I have a HTML form which has two dropdown menus and a button. One dropdown menu has 'package type' which consists of 'Gold', 'Silver' and 'Bronze'. The second dropdown menu has 'months' with 12 options (for up to 12 months) and then a calculate button.
Now, this is the bit I hope I can explain well...
If you select 'Silver', and '1 month', it will cost £150.00.
If you select 'Silver', and '2 months', it will cost £225.00.
If you select 'Silver', and '3 months', it will cost £300.00.
And so on (up to 12 months). So the logic for the above is £150.00 for the first month, and then £75 for additional months.
But if you decide you want to have a 'Gold' package, it will be as follows:
If you select 'Gold', and '1 month', it will cost £199.00.
If you select 'Gold', and '2 months', it will cost £298.50.
If you select 'Gold', and '3 months', it will cost £398.00.
And so on (up to 12 months). So the logic for the above is £199.99 for the first month, and then £99.50 for additional months.
And similar for 'Bronze' too, except 1 month is £75.00, 2 months is £112.50 (logic is £75.00 for first month, and £37.50 for additional months).
I hope this makes sense? Below is the HTML for the form, which I know does not work, but this is just to try and explain...
<form name="costcalculator">
<div class="package-type">
<select name="packageType" id="packageType">
<option value="199.00" label="Gold">Gold</option>
<option value="150.00" label="Silver">Silver</option>
<option value="75.00" label="Bronze">Bronze</option>
</select>
</div>
<div class="months">
<select name="months" id="months-bronze">
<option value="£75.00" label="1 month">1 month Bronze</option>
<option value="£112.50" label="2 months">2 months Bronze</option>
</select>
</div>
<div class="months">
<select name="months" id="months-silver">
<option value="£150.00" label="1 month">1 month Silver</option>
<option value="£225.00" label="2 months">2 months Silver</option>
</select>
</div>
<div class="months">
<select name="months" id="months-gold">
<option value="£199.00" label="1 month">1 month Gold</option>
<option value="£298.50" label="2 months">2 months Gold</option>
</select>
</div>
<button type="button" onclick="calculatePrice();showDiv();">Calculate</button>
</form>
What I currently have (that works), is the following, but it doesn't do what I need it to do, this just has the cost hardcoded in, so regardless of the package type, the cost will be the same (except for the initial cost being different for each package):
<form name="costcalculator">
<div class="package-type">
<select name="packageType" id="packageType">
<option value="199.00" label="Gold">Gold</option>
<option value="150.00" label="Silver">Silver</option>
<option value="75.00" label="Bronze">Bronze</option>
</select>
</div>
<div class="months">
<select name="months" id="months">
<option value="100.00" label="1 month">1 month</option>
<option value="200.75" label="2 months">2 months</option>
<option value="275.25" label="3 months">3 months</option>
<option value="349.00" label="4 months">4 months</option>
<option value="369.99" label="5 months">5 months</option>
<option value="450.00" label="6 months">6 months</option>
</select>
</div>
<button type="button" onclick="calculatePrice();showDiv();">Calculate</button>
</form>
And the JavaScript as follows:
function calculatePrice(costcalculator){
var elt = document.getElementById("packageType");
var package = elt.options[elt.selectedIndex].value;
var elt = document.getElementById("months");
var months = elt.options[elt.selectedIndex].value;
package = parseFloat(package);
months = parseFloat(months);
var total = package+months;
document.getElementById("TotalPrice").value=total;
}
So I thought I was nearly there with the working code above, but the more I get into it, the more I realise it's way off.
It just needs a way that when the user selects the package type in the first dropdown menu, then the second dropdown menu containing the months will (behind the scenes) have populated the new costs immediately before the user selects number of months, and then if the user then decides to select a different package to the last one, the second dropdown menu will refresh again but with the different costs in the background.
Here's a simple solution using a simple data structure as per the comment from 04FS. The data structure has the package name as the key, for easy lookup. It has the base price (for the first month) and then the price for additional months, so the total price can be easily calculated.
HTML markup:
<form name="costcalculator">
<div class="package-type">
<select name="packageType" id="packageType" onchange="setMonths(this.value)">
<option value="gold">Gold</option>
<option value="silver">Silver</option>
<option value="bronze">Bronze</option>
</select>
</div>
<div class="months">
<select name="months" id="months">
<option value="1">1 month</option>
<option value="2">2 months</option>
<option value="3">3 months</option>
<option value="4">4 months</option>
<option value="5">5 months</option>
<option value="6">6 months</option>
<option value="7">7 months</option>
<option value="8">8 months</option>
<option value="9">9 months</option>
<option value="10">10 months</option>
<option value="11">11 months</option>
<option value="12">12 months</option>
</select>
</div>
<button type="button" onclick="calculatePrice()">Calculate</button>
<div id="price"></div>
</form>
Javascript code:
var costs = {
'gold': {'basePrice': 199.99, 'pricePerMonth' : 99.5, 'maxMonths': 12},
'silver': {'basePrice': 150, 'pricePerMonth' : 75, 'maxMonths': 12},
'bronze': {'basePrice': 75, 'pricePerMonth' : 37.5, 'maxMonths': 2}
};
function setMonths(package)
{
var maxMonths = costs[package].maxMonths;
document.getElementById("months").innerHTML = ''; // Clear all options
for (var i = 1; i<=maxMonths; i++){
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i + (i > 1 ? ' months' : ' month');
document.getElementById('months').appendChild(opt);
}
}
function calculatePrice()
{
var package = document.getElementById('packageType').value;
var months = document.getElementById('months').value;
var price = costs[package].basePrice + (costs[package].pricePerMonth * (months - 1));
document.getElementById('price').innerHTML = price.toFixed(2);
}
Working sample:
https://jsfiddle.net/td3j5frn/
Or, you may go, like:
//data model
var membershipPlans = {
silver: {'1mo': 150, '2mo': 225, '3mo': 300},
gold: {'1mo': 199, '2mo': 298.5, '3mo': 398}
};
//don't punish me for that with downvotes , please :)
Array.prototype.unique = function() {
const resArr = [];
this.forEach(entry => {
if(resArr.indexOf(entry) == -1) resArr.push(entry);
})
return resArr;
};
//populate the view with possible options
const inputFields = {
package: document.getElementById('package'),
duration: document.getElementById('duration')
};
const cost = document.getElementById('cost');
inputFields.package.innerHTML = Object.keys(membershipPlans).sort().reduce((options, option) => options+=`<option value="${option}">${option}</option>`,'<option value="" selected disabled></option>');
inputFields.duration.innerHTML = Object.values(membershipPlans).map(entry => Object.keys(entry)).flat().unique().reduce((options, option) => options+=`<option value="${option}">${option}</option>`,'<option value="" selected disabled></option>');
//listen for input changes and display the cost
Object.values(inputFields).forEach(inputField => {
inputField.addEventListener('change', ()=>
cost.innerHTML = Object.values(inputFields).every(inputField => inputField.value !='') ? membershipPlans[inputFields.package.value][inputFields.duration.value]+' £' : '- £')
});
<div id="wrapper">
<span>Pick your </span>
<br>
<label>package:</label>
<select id="package" class="calcInput"></select>
<label>duration:</label>
<select id="duration" class="calcInput"></select>
<br>
<span>Your cost is:</span>
<br>
<span id="cost">- £</span>
</div>
I have a onchange multiple select option that can select multiple course then display the total price in other input values
However how to get the total price if I have another multiple select option for months to be sum up in that input
Each months's price is same
course select option code
<select class="form-control" onchange="selectFunction(event)"
name="pay_course[]" required="" multiple>
<option data-price="1111" value="courseId1">English</option>
<option data-price="2222" value="courseId2">Math</option>
</select>
month select option code
<select class="form-control" multiple="multiple" >
<option selected="selected" value="" name="pay_fee_month[]" disabled="true">Select Month...</option>
<option value='Janaury'>Janaury</option>
<option value='February'>February</option>
<option value='March'>March</option>
<option value='April'>April</option>
<option value='May'>May</option>
<option value='June'>June</option>
<option value='July'>July</option>
<option value='August'>August</option>
<option value='September'>September</option>
<option value='October'>October</option>
<option value='November'>November</option>
<option value='December'>December</option>
</select>
Input to be display the total
<input type="number" value="" id="money" class="form-control">
Script
function selectFunction(e) {
var type_id = $('select option:selected').map(function() {
return $(this).attr('data-price');
})
.get().map(parseFloat).reduce(function(a, b) {
return a + b
});
console.log(type_id)
$("#money").val( type_id );
}
I would do it another way... Completely.
What you wish to have is the total price based on selected courses multiplied by the amount of selected months.
Below, is a script that does just that... On change of both selects.
$("#courses, #months").on("change", function(){
// Get the total price of the selected courses.
var price = 0;
$("#courses").find("option:selected").each(function(){
price += $(this).data("price");
});
console.log(price);
// Get the amount of selected months.
var monthCount = $("#months").find("option:selected").length;
console.log(monthCount);
// Multiply.
var total = monthCount * price;
$("#money").val(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" id="courses" name="pay_course[]" required="" multiple>
<option data-price="1111" value="courseId1">English</option>
<option data-price="2222" value="courseId2">Math</option>
</select>
<select class="form-control" id="months" multiple="multiple" >
<option value="" name="pay_fee_month[]" disabled>Select Month...</option>
<option value='January'>January</option>
<option value='February'>February</option>
<option value='March'>March</option>
<option value='April'>April</option>
<option value='May'>May</option>
<option value='June'>June</option>
<option value='July'>July</option>
<option value='August'>August</option>
<option value='September'>September</option>
<option value='October'>October</option>
<option value='November'>November</option>
<option value='December'>December</option>
</select>
<input type="number" value="" id="money" class="form-control">
Notice that I removed the inline onchange handler and used jQuery .on()
I also removed the selected="selected" on the first month option since it also is disabled.
I try to find a solution, but I can't find it and I am not able to program it by myself. I hope you can help me.
I have 2 elements: A textfield and a drop down menu (select/options).
Based on the birth/year of a person I enter into the textfield, I want to have a related drop down values.
If the person is 0-17 years old, the values in the drop down should bei 0, 100, 200, 300, 400, 500, 600.
If the person is 18 years old or older, the values in the drop down should bei 300, 500, 1000, 1500, 2000, 2500.
Example: If I enter 1978 into the text field, the drop down menu should show the values 300, 500,…
If I enter 2002 into the text field, the drop down menu should show the values 100, 200,…
I hope it is understandable what I am looking for.
I have checked this one:
Change dropdown value based on Text Input
and also this one, which looks also similar to what I need:
jQuery - Change hidden value based on input field
But I can't make it.
A jsfiddle would be really cool!
Thank you in advance.
<input name="Year" type="text" value="" />
<select name="Results">
<option selected="selected" value="">please choose:</option>
<option value="300">300.-</option>
<option value="500">500.-</option>
<option value="1000">1000.-</option>
<option value="1500">1500.-</option>
<option value="2000">2000.-</option>
<option value="2500">2500.-</option>
</select>
<select name="Results">
<option selected="selected" value="">please choose:</option>
<option value="100">100.-</option>
<option value="200">200.-</option>
<option value="300">300.-</option>
<option value="400">400.-</option>
<option value="500">500.-</option>
<option value="600“>600.-</option>
</select>
Kind regards,
Andy
You could handle this by taking advantage of data-* attributes and using jQuery to determine which values should be shown based on your selection :
<!-- Assumes a valid year is entered -->
<input name="Year" type="text" value="" />
<!-- Notice your possible values data options -->
<select name="Results">
<option selected="selected" value="">please choose:</option>
<option value="300" data-under-18="100" data-over-18="300">300.-</option>
<option value="500" data-under-18="200" data-over-18="500">500.-</option>
<option value="1000" data-under-18="300" data-over-18="1000">1000.-</option>
<option value="1500" data-under-18="400" data-over-18="1500">1500.-</option>
<option value="2000" data-under-18="500" data-over-18="2000">2000.-</option>
<option value="2500" data-under-18="600" data-over-18="2500">2500.-</option>
</select>
<script>
$(function(){
// When your year changes...
$('[name="Year"]').change(function(){
// Check that the value is a year (assumes 4 digit number)
if(/^\d{4}/.test($(this).val())){
// Parse the value
var year = parseInt($(this).val());
// Determine the user's age
var age = new Date().getFullYear() - year;
// Use the data attributes to set each value (ignore the first one)
$('[name="Results"] option:not(:first)').each(function(){
var valueToUse = (age >= 18) ? $(this).attr('data-over-18') : $(this).attr('data-under-18');
$(this).val(valueToUse).text(valueToUse);
});
}
else{
alert('Please enter a year! (any 4-digit number will do)');
$(this).val('').focus();
}
})
})
</script>
You can see a complete working example here and demonstrated below :
https://jsfiddle.net/erjc0fna/
Basically each option has a class that identifies it as lessThan18 or over18. The ones without classes are available for either case according to what you wrote. On keyup for the textbox it then calculates the age and hides/shows the correct options.
Include jquery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
After add ids to the input(inputId) and the 2 select(select1 and select2)
<input id="inputId" name="Year" type="text" value="" />
<select id="select1" name="Results">
<option selected="selected" value="">please choose:</option>
<option value="300">300.-</option>
<option value="500">500.-</option>
<option value="1000">1000.-</option>
<option value="1500">1500.-</option>
<option value="2000">2000.-</option>
<option value="2500">2500.-</option>
</select>
<select id="select2" name="Results">
<option selected="selected" value="">please choose:</option>
<option value="100">100.-</option>
<option value="200">200.-</option>
<option value="300">300.-</option>
<option value="400">400.-</option>
<option value="500">500.-</option>
<option value="600“>600.-</option>
</select>
Code jquery
<script>
//here the code
$( document ).ready(function() {
$("#inputId").keypress(function(e)
{
if(e.which == 13) //When you press enter key one select is hide an the other is show
{
var aux = parseInt($(this).val());
if( aux >= 1999)
{
$("#select2").show();
$("#select1").hide();
}
else
{
$("#select1").show();
$("#select2").hide();
}
}
});
});
<script>
I'm trying to calculate the number of nights between two selected days of the week using jQuery for a booking system, to specify which days of the week people can arrive and depart on. I have two dropdowns, one for arrival day and one for departure day:
<select required="required" class="daypicker" id="arrivalday" name="arrivalday">
<option></option>
<option value="1">Monday</option>
<option value="2">Tuesday</option>
<option value="3">Wednesday</option>
<option value="4">Thursday</option>
<option value="5">Friday</option>
<option value="6">Saturday</option>
<option value="7">Sunday</option>
</select>
<select required="required" class="daypicker" id="departureday" name="departureday">
<option></option>
<option value="1">Monday</option>
<option value="2">Tuesday</option>
<option value="3">Wednesday</option>
<option value="4">Thursday</option>
<option value="5">Friday</option>
<option value="6">Saturday</option>
<option value="7">Sunday</option>
</select>
If either of the dropdowns change, it should calculate the number of nights as follows:
arrival = Monday
departure = Friday
number of nights = 4
arrival = Monday
departure = Monday
number of nights = 7
arrival = Friday
departure = Monday
number of nights = 3
This is what I have so far, but nothing is happening:
$(document).ready(function(){
$(".daypicker").change(function(){
var arrivalday = $("#arrivalday").val();
var departureday = $('#departureday').val();
if (arrivalday == departureday){
$('#numnights').html('7');
} else if (arrivalday < departureday) {
$('#numnights').html(departureday - arrivalday);
} else {
$('#numnights').html(arrivalday- departureday - 1);
}
}).change();
});
Found the issue, the selects are displayed after a user selects an option, so I moved the code into the change function of that option and everything worked as expected.
You already got it, you just needed to create the container for the output (the numnights element).
Anyway the code is a little bit cleaner in this way:
$(document).ready(function(){
$(".daypicker").on('change', function(){calculateNights();});
});
function calculateNights() {
var arrivalday = $("#arrivalday").val();
var departureday = $('#departureday').val();
var numberNights = departureday - arrivalday;
numberNights = (numberNights < 1) ? numberNights + 7 : numberNights;
$("#numNights").html(numberNights);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select required="required" class="daypicker" id="arrivalday" name="arrivalday">
<option></option>
<option value="1">Monday</option>
<option value="2">Tuesday</option>
<option value="3">Wednesday</option>
<option value="4">Thursday</option>
<option value="5">Friday</option>
<option value="6">Saturday</option>
<option value="7">Sunday</option>
</select>
<select required="required" class="daypicker" id="departureday" name="departureday">
<option></option>
<option value="1">Monday</option>
<option value="2">Tuesday</option>
<option value="3">Wednesday</option>
<option value="4">Thursday</option>
<option value="5">Friday</option>
<option value="6">Saturday</option>
<option value="7">Sunday</option>
</select>
<hr>
<div id="numNights"></div>
Hope it helps!
How to make that the all selected options, not the values, but the actual text, would be displayed somewhere?
Html:
<h1>Made your PC:</h1>
<div>
<label>Processeor: </label><select id="processor" name="processor">
<option class="label" value>Select Processor</option>
<!-- Home Ware -->
<option value="P1">Processor 1</option>
<option value="P2">Processor 2</option>
<option value="P3">Processor 3</option>
<option value="P4">Processor 4</option>
</select>
</div>
<p><strong>Only compatible components will show.</strong></p>
<div>
<label>Select motherboard: </label><select id="motherboard" name="motherboard" class="subcat" disabled="disabled">
<option class="label" value>Select Motherboard</option>
<!-- Home Ware -->
<option rel="P1 P2" value="AS1">ASUS RAMPAGE V EXTREME</option>
<option rel="P2 P3" value="AS2">ASUS ATX DDR3 2600 LGA</option>
<option rel="P1 P3 P4" value="GB1">Gigabyte AM3+</option>
<option rel="P2 P4" value="MSI1">MSI ATX DDR3 2600 LGA 1150</option>
</select>
</div>
<div>
<label>Select RAM: </label> <select disabled="disabled" class="subcat" id="RAM" name="RAM">
<option class="label" value>RAM Memory</option>
<option rel="AS1 AS2 GB1" value="KI1">Kingston Value RAM</option>
<option rel="AS1 AS2 MSI1" value="P5KPL">P5KPL-AM SE</option>
<option rel="MSI1 GB1" value="960GM">960GM-VGS3 FX </option>
</select>
</div>
<div>
<label>Select Video Board: </label> <select disabled="disabled" class="subcat" id="video-card" name="video-card">
<option class="label" value>Video Card</option>
<option rel="MSI1 AS2" value="EVGA8400">EVGA GeForce 8400 GS</option>
<option rel="AS1" value="XFXAMD">XFX AMD Radeon HD 5450</option>
<option rel="MSI1 GB1" value="GTX750Ti">EVGA GeForce GTX 750Ti SC</option>
</select>
</div>
Javascript:
$(function(){
var $supcat = $("#processor"),
$cat = $("#motherboard"),
$subcat = $(".subcat");
$supcat.on("change",function(){
var _rel = $(this).val();
$cat.find("option").attr("style","");
$cat.val("");
if(!_rel) return $cat.prop("disabled",true);
$cat.find("[rel~='"+_rel+"']").show();
$cat.prop("disabled",false);
});
$cat.on("change",function(){
var _rel = $(this).val();
$subcat.find("option").attr("style","");
$subcat.val("");
if(!_rel) return $subcat.prop("disabled",true);
$subcat.find("[rel~='"+_rel+"']").show();
$subcat.prop("disabled",false);
});
});
I tried this one code that was posted earlier, but it only display one selection, right after picking, is there any way it could display all the selections and with my random text, like "Your selections"?:
<script>
function myNewFunction(sel)
{
alert(sel.options[sel.selectedIndex].text);
}
</script>
<select id="box1" onChange="myNewFunction(this);" >
<option value="98">dog</option>
<option value="7122">cat</option>
<option value="142">bird</option>
</select>
This should give the actual label text, not the value, for a given select-element.
$(selector).find(":checked").html()
So if you want to show all of them, you could do something like this:
$("#video-card").on("change", function () {
var choices = [];
$("select").each(function() {
choices.push($(this).find(":checked").html());
});
alert("You selected: " + choices.join(', '));
})
And here's a codepen for demo purposes
http://codepen.io/anon/pen/XbjKYQ
function myNewFunction(sel) {
alert($(sel).val());
}
This should actually be working.
If that doesn't work, try to place a window.setTimeout(function() { ... }, 10); around your alert. It's possible that the browser calls the myNewFunction() method before it updates the selection value when the user clicks on one option.
EDIT: If you want the text instead of the value, use
alert($(sel).find("option:selected").text());
You need to loop through each of the selects, not just the first one:
function updateOutput() {
var selects = document.getElementsByTagName('SELECT');
var output = document.getElementById('output');
var arr = [];
for (i=0; i < selects.length; i++) {
arr.push(selects[i].options[selects[i].selectedIndex].text);
}
output.innerHTML = arr.join('; ');
return arr;
}
In this case, I push all the values into an array and then join the array values at the end to create the final string.
I updated a codepen provided earlier: http://codepen.io/anon/pen/WvGxgz