Using onchange event handler to alter second select list - javascript

Have a form field asking for a product, these are various sizes, the second form field asks for the quantity.
The stock quantity of each product is shown in the first select, I want the second select to be a maximum of the stock available so customers cannot order more than I have available.
This is the first select (also linked to show custom pictures) Site is ASP
<select name="barcode" id="imageselect">
<option value>Please Select .....</option>
<option value="322974">6.6lbs 100m - £21.00 ( 2 in stock )</option>
<option value="322975">8.2lbs 100m - £21.00 ( 3 in stock )</option>
<option value="322976"disabled=disabled>10.4lbs 100m - £21.00 - Out of stock</option>
<option value="323656">13.7lbs 100ms - £21.00 ( 4 in stock )</option>
</select>
This is the second select:
<select name="quantity">
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
Have tried using onchange event but with no joy.
The UK Autotrader has a very good example of this working with their car makes / models.

This should do what you want...
NB: I've used a shot cut by adding a 'stock' attribute to your options, just to avoid parsing the string.
<option value="322974">6.6lbs 100m - £21.00 ( 2 in stock )</option>
If you want to avoid this, the example below also shows you how to get the text to parse for the stock attribute.
$("#imageselect").change(function(event){
var $this = $(this),
value = $this.val();
var $option = $("option[value="+value+"]", $this),
text = $option.text(), // you could parse this to get stock OR
stock = parseInt($option.attr('stock')); // short-cut: use stock attr
// only show the first n options:
var $opts = $("select[name=quantity] option");
$opts.hide().slice(0, stock).show();
});

The second select will show the maximum stock. So what you need to do is store the values in the database, fetch max value and as you are using asp , call the page with ajax which will be shown here as a select option

Related

Dynamic select element

I have this select element with multiple option inside it:
<select class="form-control" name="genere1">
<option value="Alternative / Indie">Alternative / Indie</option>
<option value="Classical Music">Classical Music</option>
<option value="Country">Country</option>
<option value="Easy Listening">Easy Listening</option>
<option value="Electronic / Dance">Electronic / Dance</option>
<option value="Hip Hop / Rap">Hip Hop / Rap</option>
<option value="Jazz">Jazz</option>
<option value="Latin / Reggaeton">Latin / Reggaeton</option>
<option value="Other">Other</option>
<option value="Pop">Pop</option>
<option value="Reggae / Dancehall">Reggae / Dancehall</option>
<option value="Rock">Rock</option>
<option value="Spiritual">Spiritual</option>
</select>
for every option element you see up here i have another select element. Basically, I have a series of music genres listed in a select element and, under it, the subgenres related to every single one of the "master genres".
What I would like to do is make the subgenres visible only when the relative genre is selected. For example, if the user selects "Pop", I would like to show them the related select field containing the Pop subgenres.
My HTML markup is actually generated by a WordPress plugin and I am not able to edit it, unfortunately. This being said, I can't declare custom values inside my HTML because they are automatically generated by the plugin. I am actually looking for a simple solution, something like: if 'master genre' is 'rock', then display 'rock' input subgenres. How could I do something like this?
You could link two selects and display corresponding subgenres using .dataset.option. I'm afraid you won't get around a little JavaScript here.
Here's a working example for your particular use-case:
const genre = document.querySelector("#genre");
const subgenre = document.querySelector("#subgenre");
const subOptions = subgenre.querySelectorAll("option");
const setValue = (newValue) => {
subgenre.innerText = null;
for (let i = 0; i < subOptions.length; i++)
subOptions[i].dataset.option === newValue &&
subgenre.appendChild(subOptions[i]);
};
setValue(genre.value);
<select id="genre" onchange="setValue(this.value)">
<option value="Metal">Metal</option>
<option value="Rock">Rock</option>
</select>
<select id="subgenre">
<option value="Metal" data-option="Metal">Thrash Metal</option>
<option value="Metal" data-option="Metal">Death Metal</option>
<option value="Metal" data-option="Metal">Black Metal</option>
<option value="Rock" data-option="Rock">Classic Rock</option>
<option value="Rock" data-option="Rock">Hard Rock</option>
</select>

set a html option selected in a dropdown containing optgroup tag using javascript

I'm working With Html(JSP) and Javascript. I have a dropdown box with id "examcenter" containing many optgroup as shown in the following code. in the function loadDrivingSchool() in javascript, I would like to set selected the value of the selected element. the loadDrivingSchool() function calls a controller in a server and when I return the view, the dropdown list does not have a selected value. I want to set this selected value to the value that the user choose before the reloading of the page. I have try the following Javascript code but it is not working:
document.getElementById('examcenter').getElementsByTagName('option')[examCenter].selected = 'selected' ;
<select id="examcenter" onchange="loadDrivingSchool();">
<optgroup label="ADAMAOUA">
<option value="1">TIBATI</option>
<option value="2">TIGNERE</option>
<option value="3">MEIGANGA</option>
<option value="4">BANYO</option>
<option value="5">NGAOUNDERE</option>
</optgroup>
<optgroup label="CENTRE">
<option value="6">YAOUNDE</option>
<option value="7">ESEKA</option>
<option value="8">AKONOLINGA</option>
<option value="9">NANGA EBOKO</option>
<option value="10">MONATELE</option>
<option value="11">MBALMAYO</option>
<option value="12">MFOU</option>
<option value="13">NGOUMOU</option>
<option value="14">BAFIA</option>
<option value="15">NTUI</option>
</optgroup>
<optgroup label="EXTREME NORD">
<option value="20">MAROUA</option>
<option value="21">KAELE</option>
<option value="22">KOUSSERI</option>
<option value="23">MORA</option>
<option value="24">YAGOUA</option>
<option value="25">MOKOLO</option>
</optgroup>
<optgroup label="EST">
<option value="16">YOKADOUMA</option>
<option value="17">ABONG-MBANG</option>
<option value="18">BATOURI</option>
<option value="19">BERTOUA</option>
<option value="62">NGUELEMENDOUKA</option>
</optgroup>
</select>
What I think you are trying to do is keep a track of what the user has selected, without submitting that selected option. That can only be achieved if you keep a record of that in some way, possibly using the session attribute.
You can probably store the value of the selected options in a session and then get it's value using AJAX.
But if I am wrong and you are trying to just simply get the value of the selected option without leaving that page, then you can try this to display the value of the selected option in your dropdown:
alert( document.getElementById("examcenter").value );
Also, I see a problem in your code. You are using
document.getElementById('examcenter').getElementsByTagName('option')[examCenter].selected = 'selected' ;
Instead, you should use:
document.getElementsByTagName('option').selected = true ;

drop-down values referenced from another drop-down value

I am making a bookings page for a movie theater. I would like the user to be able to choose days in which movies are showing and then based off the day, the sessions that are available.
For example, the first drop-down menu displays movies currently showing. if someone wants to see Pixels, then the second drop down menu displays the days Pixels is showing. Once the user selects a day, then the third drop down menu will provide the times that Pixels is showing on that particular day.
<label>Movie Name:
<select id="movie" name="movie">
<option selected="selected" value="">Please select a movie</option>
<option value="Pixels">Pixels</option>
<option value="Straight_Outta_Compton">Straight Outta Compton</option>
<option value="Last_Cab_To_Darwin">Last Cab To Darwin</option>
<option value="Nicki_and_The_Flash">Nicki and The Flash</option>
</option>
</select>
</label>
</br>
<label>Session Day:
<select id="day" name="day">
<option selected="selected" value="">Please select...</option>
<option value="Monday">Monday</option>
<option value="Tuesday">Tuesday</option>
<option value="Wednesday">Wednesday</option>
<option value="Thursday">Thursday</option>
<option value="Friday">Friday</option>
<option value="Saturday">Saturday</option>
<option value="Sunday">Sunday</option>
</select>
</label>
</br>
<label>Session Time:
<select id="time" name="time">
<option selected="selected" value="">Please select...</option>
<option value="1200">12:00</option>
<option value="1300">13:00</option>
<option value="1500">15:00</option>
<option value="1800">18:00</option>
<option value="2100">21:00</option>
</select>
</label>
Lets say Pixels shows on Mondays and Tuesdays and the only times it shows is at 13:00 and 18:00. How would i write the jQuery to provide this sort of functionality?
A quick exemple on how you can handle this :
JS
$("#movie").on("change", function(){
$("#day option, #time option").hide();
var days = $("option:selected", this).attr("data-days").split(",");
var times = $("option:selected", this).attr("data-times").split(",");
for(i=0; i<days.length; i++){
$("#day option[value="+days[i]+"]").show();
}
for(i=0; i<times.length; i++){
$("#time option[value="+times[i]+"]").show();
}
});
CSS
#day option, #time option{
display:none;
}
You have to store all informations about each movie in data-days and data-times attribute.
This way, once selected, you can retrieve all this informations, split them, and display corresponding <option>
Be carreful, you have a useless </option> tag at the end of your "#movie" <select></select>
Live Demo
Edit 1:
From your comment, the solution I can provide could look like this exemple
First, store all info in a data- attribute, like day1[time1,time2];day2[time1,time2] and so one.
After some split() & substring() on #movie .change() event, you can dynamically add specific options for the #day select tag (which will now look like <option value="Monday" data-times="13:00,18:00">Monday</option>).
Same as before, just make a function that will handle the data-times on #day .change() event to dynamically create the desired #time options

Not able to get value from the dynamically generated drop down

Problem
I've 2 diff drop down select box. First select box is static whereas the other is dynamically generated according to the value selected in first select box. The values are getting generated properly but when I try to display the value of second select box it only display the first option's value, even if selected 3rd or 4th option. Please see code and example below:
Javascript Code
function wpPopulate(){
$('#win_parameter').empty();
var classes = document.getElementById('noOfClasses').value;//total number of classes
var percent = (100/classes);//to get a percentage for single class
//console.log("1 class: "+percent+"%");
//Define Variables
var wpOptions = '';
var dd = '';
for(var i=1; i<=classes; i++){
dd = parseFloat(percent*i).toFixed(2)+"% ("+i+" class)";
wpOptions += '"'+parseFloat(percent*i).toFixed(2)+'": "'+dd+'", ';
}
wpOptions = "{"+wpOptions.substr(0, (wpOptions.length-2))+"}";
wpOptions = $.parseJSON(wpOptions);
var selectValues = wpOptions;
$.each(selectValues, function(key, value) {
$('#win_parameter')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
}
HTML Code:
(Select box 1)
<select name="noOfClasses" id="noOfClasses" onChange="wpPopulate();">
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
(Select box 2)
<select name="win_parameter" id="win_parameter">
</select>
Example:
When selected 5 classes in first select box the options come in second select box are as follows. When I select anything apart from 20% it still displays as 20%, example 60%. Any help or guidance will be much appreciated!!
<select name="win_parameter" id="win_parameter">
<option value="20.00">20.00% (1 class)</option>
<option value="40.00">40.00% (2 class)</option>
<option value="60.00">60.00% (3 class)</option>
<option value="80.00">80.00% (4 class)</option>
<option value="100.00">100.00% (5 class)</option>
</select>

Modify subsequent dropdown list with jquery

I have a web form with multiple dropdown lists. I would like to only display options in the second list that share the same value as the selection in the first list.
<!-- Dropdown #1 -->
<div class="control-group">
<label class="control-label" for="select01">Select Tier</label>
<div class="controls">
<select id="select01">
<option value="all">All Tiers</option>
<option value="db">Database Tier</option>
<option value="app">Application Tier</option>
<option value="web">Web Tier</option>
</select>
</div>
</div>
<!-- Dropdown #2 -->
<div class="control-group">
<label class="control-label" for="select01">Select Audit Point</label>
<div class="controls">
<select id="select03">
<option value="all">Software Version</option>
<option value="all">Server OS, Memory, CPU</option>
<option value="all">High Availability</option>
<option value="db">DBMS Version</option>
<option value="db">DBMS Statistics</option>
<option value="db">DBMS Parameters</option>
<option value="db">DBMS Data File Growth</option>
<option value="db">Database Disk Structure</option>
<option value="db">Long Running SQL</option>
<option value="db">Security Data Growth Range</option>
<option value="db">Extraneous entries in System Tables</option>
<option value="db">Feed Error Orphans</option>
<option value="db">Position Detail Orphans</option>
<option value="db">Data Retention Policy</option>
<option value="db">Securities Added Daily</option>
<option value="db">Security Master Load</option>
<option value="db">SRM Purge</option>
<option value="db">Best Pricing Purge</option>
<option value="db">Partitioning</option>
<option value="db">DBMS Data/Log File Utilize Shared Disk</option>
<option value="db">DBMS Failover</option>
<option value="app">DBMS Client Version</option>
<option value="app">Star Engine IP Configuration</option>
<option value="app">Engine Count/Configuration</option>
<option value="app">STAR Engine Logging Interval</option>
<option value="app">PACE Engine Port Configuration</option>
<option value="app">PACE Server Logging</option>
<option value="app">PACE Engine Log Configuration</option>
<option value="app">STAR Engine Load Balancer Interval</option>
<option value="app">Engines Restarted Weekly</option>
<option value="app">Designated Master</option>
<option value="app">Cluster Managers Identical</option>
<option value="app">Uploader Shared Disk Space</option>
<option value="app">Custom Archive Rule Shared Disk Space</option>
<option value="app">App Server Clustering</option>
<option value="app">PACE Event Concurrency</option>
<option value="web">Homogenous Engine Configuration</option>
<option value="web">Log Levels</option>
<option value="web">Scheduler Purging</option>
<option value="web">Web Server Services Restarted Weekly</option>
<option value="web">Email Notification Basic Configuration</option>
<option value="web"n>Web Load Balancer Configuration</option>
<option value="web">Load Balancer Customizations</option>
<option value="web">Portal Shared Disk Space</option>
<option value="web">Message Center Shared Disk Space</option>
<option value="web">Message Center ID'S</option>
<option value="web">Schedule Service Config</option>
<option value="web">ePace is a client of Clustered App Servers</option>
<option value="web">Portal is a client of Clustered App Servers</option>
<option value="web">ESTAR is a client of Clustered Load Balancers</option>
<option value="web">ESTAR is a client of Clustered Engines</option>
<option value="web">ESTAR is a client of Clustered Report Export Services</option>
<option value="web">WebSync Configured</option>
<option value="web">Web Server Load Balancing Configured</option>
<option value="web">Shared Disk Dynamic Folder</option>
I need to be able to continuously change the list 1 selection, so I cannot .remove() unmatched options in the 2nd list. If I did remove them, I would then need to re-populate the 2nd list on each new selection from the 1st list.
Thank you for your help.
I have tested with your HTML-Code and works properly... You only have to modify this code so that there will be a filtered selection when loading the page.
jQuery(document).ready(function() {
var savedOptions = '';
savedOptions = jQuery('#select03').html(); //save the second dropdown-list
jQuery('#select01').change(function() {
var selectedValue = jQuery('#select01').val(); //After changing the value of the first dropdown, store this value inside a variable
jQuery('#select03').html(savedOptions); //restore the content of the 2nd dropdown
jQuery('#select03').children('option').each(function() {
if(jQuery(this).attr('value') != selectedValue) {
jQuery(this).remove(); //Compare and step through the 2nd dropdown and delete all unneccessary options
}
});
});
});
You can disable the options like so:
$("#select01").change(function() {
//Get value from the selected option
var filter = this.value;
//Loop thru second select options
$("#select02 option").each(function() {
//Enable the option (used for if the select changes values)
$(this).prop("disabled", false);
//Compare second select values to the initial selected value
if (this.value != filter) {
//Disable options that do not match
$(this).prop("disabled", true);
}
});
});
Demo: http://jsfiddle.net/QXhRy/
I suppose you could also completely remove the options as well, however, this would involve re-building the select each time you change the initial dropdown.
You cannot have duplicated option values inside the select element.
It is better you have a separate element that holds the options tag. And then replace the value with data-value attributes.
Try this
$('#select01').on('change', function() {
var $select03 = $('#select03'),
currValue = this.value;
$select03.empty();
var $options = $('.template option').filter(function() {
return $(this).data('value') === currValue
}).get();
$select03.append($options);
}).change();
Working Fiddle
Create a "map" of String arrays and populate from this as needed.
// initialize options on page load
var options = new Array();
options["all"] = new Array("A","B","C");
options["db"] = new Array("D","E","F");
function changeSecondDropDown(selectedValue)
{
// clear options from second drop down list
...
var optionsToAdd = options[selectedValue]
// loop through options and add them to second drop down list
...
}

Categories

Resources