Dependent Dropdown menus - javascript

Hi everyone I'm fairly new and unfamiliar with JavaScript/Web Dev and I'm trying to make two dropdown menus, where the second menu changes depending on what they choose on the first one
for example
Choice1
Choice2
Choice3
and if they choose Choice1 the next drop down might be
Choice1.1
Choice1.2
and a follow up question would be, how can I get what the User chose?
This also does not have to be written in javascript.
Any help/resources/readings would be very helpful (I've tried doing google searches but I couldn't find anything)
Thank you!

I have created simple demo app for you, give it a try.
Further study reference
http://api.jquery.com/
http://www.w3schools.com/jquery/default.asp
https://api.jquery.com/change/ - To understand more on change event
$("#select_1").on("change", function(evt) { //Using jQuery subscribe for change event of select_1
var $select_2 = $("#select_2");
$select_2.empty(); //Empty the select before adding new items.
for (i = 0; i < 5; i++) {
$select_2.append($("<option>Sub choice " + $(this).val() + "__" + i + "</option>"));
}
});
$("#select_1").change(); //Trigger change event on page load so that the second select gets properly set
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Choices</label>
<select id="select_1">
<option value='1'>Choice 1</option>
<option value='2'>Choice 2</option>
</select>
<BR />
<label>Sub Choices</label>
<select id="select_2">
<option>Please select</option>
</select>

Related

Materialize Multiple Select - Show the number of items selected

Good Afternoon
I am using materialize multiple select for the user select multiples values, but instead of displaying each value in the input I want to show:
"Selected: 5"
In other words, I want to show the quantity of elements that the user selected, so this way the user will have a clean input, but I've tried many approaches and I didn't achieve this.
I was able to get the amount of items checked by the user, but when I've tried to set using the id of the select or the id of the div/input I didn't achieve this result, practically using the select id I can set the values but this one that I want makes the multiple select stay with the last value selected and using the id of the div doesn't change anything.
Below you will find the code that I've tried.
I hope that someone knows a way to tricky and achieve this.
FIDDLE: https://jsfiddle.net/dp90tgju/
<div id="myInput" class="input-field">
<select id="filterOptions" multiple>
<option value="" disabled>Choose your option</option>
<option value="1">Toys</option>
<option value="2">Comics</option>
<option value="3">Magazines</option>
<option value="4">Gym</option>
</select>
<label>Filter</label>
</div>
$("#filterOptions").on('change', function() {
console.log($(this).val());
if($(this).val().length !== null){
var numberOfElements = $(this).val().length;
console.log("Number:" + numberOfElements);
$(this).val("Selected");
}
$("#myInput").val('Selected: 2');
});
Thanks for the help

Assigning a selected option from a dropdown to a variable in jquery

I want to assign the chosen option from the dropdown to become the selectedSubject variable but am having problems with it, I had code which half worked...
selectedSubject = $('select#subject-options').val();
But when a different option is selected it doesn't change??
And need it change for the game I am creating
HTML:
<p>Subjects</p>
<select id="subject-options" name="subject-options">
<option selected disabled >Please Choose</option>
<option id="BBT" value="$BBT">Big Bang Theory</option>
<option value="$LOTR">Lord Of The Rings</option>
<option value="$EPL">EPL Football Teams</option>
<option value="$ASIA">Asian Countries</option>`
</select>
Jquery:
const $BBT = ['sheldon','leanord','spock','cheescake``factory','howard','raj','star` `trek','penny','amy','bernadette','physics','laundry','halo` `night','dumplings', 'brisket','nasa','string theory','dark matter',` `'comiccon'];
let selectedSubject = $BBT;
selectedSubject = selectedSubject[Math.floor(Math.random() * selectedSubject.length)];
I have been through 7 different questions similar and couldn't find anything that helped me, so if anyone could help me directly or direct me to another question that has been answered that will help me in my troubles.
You must add an event handler to #subject-options to update the selectedSubject variable each time you change your selection.
$('#subject-options').on('change', function() {
selectedSubject = $('#subject-options option:checked').val();
});
JS Bin
In your jQuery selector you grab the select object itself. You need the option object and especially the one that is selected.
selectedSubject = $('select#subject-options option:selected').val();

How to select multiple select options with selenium

I am writing a test using Selenium Webdriver. I want to select the second option of every dropdown menu that may appear on the page. The number of dropdown menus will be different every time.
This is what I've come up with and It does not work:
if (driver.findElements({tagName: 'select'})) {
var select = driver.findElements({tagName: 'select'});
for (i = 0; i < select.length; i ++) {
i++;
driver.findElement(webdriver.By.xpath('//select['+i+']/option[2]')).click();
}
}
HTML:
<select class="form-control" name="answer_4282670">
<option value="0">Please choose one...</option>
<option value="option a">option a</option>
<option value="option b">option b</option>
<option value="option c">option c</option>
<option value="Other" data-other-flag="">Other</option>
</select>
The value of each option will be different in each instance, so we can not choose anything by its value
How can I fix this so it will click the second option of a menu for each one that will show up (if one shows up)?
I am using webdriver js, and nth child works for me:
driver.click('#my_select_box').click('#my_select_box option:nth-child(3)')
I know that this is not a direct anwser, but i cant comment your post yet so i hope you are fine with that.
I havent worked with selenium myself, but i wanted to start using it, and I tried to learn alot from this website: https://code.google.com/p/selenium/wiki/AdvancedUserInteractions and after doing some research i found a similar question. how to select element in multi select box in selenium webdriver The big difference is, that the anwser was given in java.
Even though its not the perfect solution I hope those 2 links can help you, and again sorry that I cant write that as a comment
You can apply this logic: define a list variable with accessing second option of all dropdown like .form-control > option:nth-child(3) then iterete over this and call .click event for each item.
if (driver.findElements({css: '.form-control > option:nth-child(3)'})) {
var selects = driver.findElements({css: '.form-control > option:nth-child(3)'});
for (i = 0; i < selects.length; i ++) {
selects[i].click()
}
}

capturing the clicked option in bootstrap selectpicker [duplicate]

On a page, I have a select (multiple) box with many options.
Now I want to react on the last clicked item to display some data with ajax.
As the "click" event on the option element does not work in IE, I currently use the "change" event.
The problem is, that the "value" and the selectedIndex attribute point to the first selected item, even if I select other options following the first.
The only way I could get the most recently selected option is by comparing the set of selected options before and after the "change" event.
Is there any other way?
The only way I could get the most
recently selected option is by
comparing the set of selected options
before and after the "change" event.
That's probably your best bet -- ie's not going to report click events on the individual options (it will only report clicks on the select box).
If you really want to figure out which option was clicked (when listening for clicks on the select box itself), you can look at the offsetY property of the event object (which will be the vertical offset of the mouse cursor relative to the top of the first option in the select box -- so it includes the select box's scroll offset), and divide that by your pre-determined option size (which will depend on the font-size of the select box).
But obviously, that won't help you when the user selects options via the keyboard.
The following code is not perfect. I think it doesn't work entirely correctly in IE6 but it is fine in IE7-8, Firefox, Safari(Win), Opera & Chrome. It only records the last click to select a value so un-selecting a value that was the last selected without selecting another still returns the last selected (now unselected) index. I'll leave you to handle that if you need to...
<html>
<head>
<title>Multiple selection indices attribute</title>
<script type='text/JavaScript'>
function oc(a) {var o={};for (var i=0;i<a.length;i++) {o[a[i]]='';}; return o;};
function getIndices(ele)
{if (!ele.prevSelected) {ele.prevSelected=new Array();}
ele.selectedIndices=new Array();
while (ele.selectedIndex != -1)
{ele.selectedIndices.push(ele.selectedIndex);
if (ele.selectedIndex in oc(ele.prevSelected)) {null;}
else {ele.newIndex = ele.selectedIndex;}
ele.options[ele.selectedIndex].selected = false;
};
for (var i=0;i<ele.selectedIndices.length;i++)
{ele.options[ele.selectedIndices[i]].selected = true;};
ele.prevSelected=new Array();
if (ele.selectedIndices)
{for (var i=0;i<ele.selectedIndices.length;i++)
{ele.prevSelected.push(ele.selectedIndices[i]);}
}
};
function display(ele) {if (ele.newIndex) {alert('Last selection: '+ele.newIndex);}};
</script>
</head>
<body onload='getIndices(document.getElementById("mine"));'>
<select multiple='multiple' id='mine' size='10' onclick='getIndices(this);'>
<option value='A'> 0</option><option value='B'> 1</option>
<option value='C'> 2</option><option value='D'> 3</option>
<option value='E'> 4</option><option value='F'> 5</option>
<option value='G'> 6</option><option value='H'> 7</option>
<option value='I'> 8</option><option value='J'> 9</option>
<option value='K'>10</option><option value='L'>11</option>
<option value='M'>12</option><option value='N'>13</option>
<option value='O'>14</option><option value='P'>15</option>
</select>
<input type='button' value='Show' onclick='display(document.getElementById("mine"));' />
</body>

Is there an onSelect event or equivalent for HTML <select>?

I have an input form that lets me select from multiple options, and do something when the user changes the selection. Eg,
<select onChange="javascript:doSomething();">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
Now, doSomething() only gets triggered when the selection changes.
I want to trigger doSomething() when the user selects any option, possibly the same one again.
I have tried using an "onClick" handler, but that gets triggered before the user starts the selection process.
So, is there a way to trigger a function on every select by the user?
Update:
The answer suggested by Darryl seemed to work, but it doesn't work consistently. Sometimes the event gets triggered as soon as user clicks the drop-down menu, even before the user has finished the selection process!
I needed something exactly the same. This is what worked for me:
<select onchange="doSomething();" onfocus="this.selectedIndex = -1;">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
Supports this:
when the user selects any option, possibly the same one again
Here is the simplest way:
<select name="ab" onchange="if (this.selectedIndex) doSomething();">
<option value="-1">--</option>
<option value="1">option 1</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
</select>
Works both with mouse selection and keyboard Up/Down keys whes select is focused.
I had the same problem when I was creating a design a few months back. The solution I found was to use .live("change", function()) in combination with .blur() on the element you are using.
If you wish to have it do something when the user simply clicks, instead of changing, just replace change with click.
I assigned my dropdown an ID, selected, and used the following:
$(function () {
$("#selected").live("change", function () {
// do whatever you need to do
// you want the element to lose focus immediately
// this is key to get this working.
$('#selected').blur();
});
});
I saw this one didn't have a selected answer, so I figured I'd give my input. This worked excellently for me, so hopefully someone else can use this code when they get stuck.
http://api.jquery.com/live/
Edit: Use the on selector as opposed to .live. See jQuery .on()
Just an idea, but is it possible to put an onclick on each of the <option> elements?
<select>
<option onclick="doSomething(this);">A</option>
<option onclick="doSomething(this);">B</option>
<option onclick="doSomething(this);">C</option>
</select>
Another option could be to use onblur on the select. This will fire anytime the user clicks away from the select. At this point you could determine what option was selected. To have this even trigger at the correct time, the onclick of the option's could blur the field (make something else active or just .blur() in jQuery).
If you really need this to work like this, I would do this (to ensure it works by keyboard and mouse)
Add an onfocus event handler to the select to set the "current" value
Add an onclick event handler to the select to handle mouse changes
Add an onkeypress event handler to the select to handle keyboard changes
Unfortunately the onclick will run multiple times (e.g. on onpening the select... and on selection/close) and the onkeypress may fire when nothing changes...
<script>
function setInitial(obj){
obj._initValue = obj.value;
}
function doSomething(obj){
//if you want to verify a change took place...
if(obj._initValue == obj.value){
//do nothing, no actual change occurred...
//or in your case if you want to make a minor update
doMinorUpdate();
} else {
//change happened
getNewData(obj.value);
}
}
</script>
<select onfocus="setInitial(this);" onclick="doSomething();" onkeypress="doSomething();">
...
</select>
The onclick approach is not entirely bad but as said, it will not be triggered when the value isn't changed by a mouse-click.
It is however possible to trigger the onclick event in the onchange event.
<select onchange="{doSomething(...);if(this.options[this.selectedIndex].onclick != null){this.options[this.selectedIndex].onclick(this);}}">
<option onclick="doSomethingElse(...);" value="A">A</option>
<option onclick="doSomethingElse(..);" value="B">B</option>
<option onclick="doSomethingElse(..);" value="Foo">C</option>
</select>
I know this question is very old now, but for anyone still running into this problem, I have achieved this with my own website by adding an onInput event to my option tag, then in that called function, retrieving the value of that option input.
<select id='dropdown' onInput='myFunction()'>
<option value='1'>1</option>
<option value='2'>2</option>
</select>
<p>Output: </p>
<span id='output'></span>
<script type='text/javascript'>
function myFunction() {
var optionValue = document.getElementById("dropdown").value;
document.getElementById("output").innerHTML = optionValue;
}
</script>
Going to expand on jitbit's answer. I found it weird when you clicked the drop down and then clicked off the drop down without selecting anything. Ended up with something along the lines of:
var lastSelectedOption = null;
DDChange = function(Dd) {
//Blur after change so that clicking again without
//losing focus re-triggers onfocus.
Dd.blur();
//The rest is whatever you want in the change.
var tcs = $("span.on_change_times");
tcs.html(+tcs.html() + 1);
$("span.selected_index").html(Dd.prop("selectedIndex"));
return false;
};
DDFocus = function(Dd) {
lastSelectedOption = Dd.prop("selectedIndex");
Dd.prop("selectedIndex", -1);
$("span.selected_index").html(Dd.prop("selectedIndex"));
return false;
};
//On blur, set it back to the value before they clicked
//away without selecting an option.
//
//This is what is typically weird for the user since they
//might click on the dropdown to look at other options,
//realize they didn't what to change anything, and
//click off the dropdown.
DDBlur = function(Dd) {
if (Dd.prop("selectedIndex") === -1)
Dd.prop("selectedIndex", lastSelectedOption);
$("span.selected_index").html(Dd.prop("selectedIndex"));
return false;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="Dd" onchange="DDChange($(this));" onfocus="DDFocus($(this));" onblur="DDBlur($(this));">
<option>1</option>
<option>2</option>
</select>
<br/>
<br/>Selected index: <span class="selected_index"></span>
<br/>Times onchange triggered: <span class="on_change_times">0</span>
This makes a little more sense for the user and allows JavaScript to run every time they select any option including an earlier option.
The downside to this approach is that it breaks the ability to tab onto a drop down and use the arrow keys to select the value. This was acceptable for me since all the users click everything all the time until the end of eternity.
To properly fire an event every time the user selects something(even the same option), you just need to trick the select box.
Like others have said, specify a negative selectedIndex on focus to force the change event. While this does allow you to trick the select box, it won't work after that as long as it still has focus. The simple fix is to force the select box to blur, shown below.
Standard JS/HTML:
<select onchange="myCallback();" onfocus="this.selectedIndex=-1;this.blur();">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
jQuery Plugin:
<select>
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<script type="text/javascript">
$.fn.alwaysChange = function(callback) {
return this.each(function(){
var elem = this;
var $this = $(this);
$this.change(function(){
if(callback) callback($this.val());
}).focus(function(){
elem.selectedIndex = -1;
elem.blur();
});
});
}
$('select').alwaysChange(function(val){
// Optional change event callback,
// shorthand for $('select').alwaysChange().change(function(){});
});
</script>
You can see a working demo here.
first of all u use onChange as an event handler and then use flag variable to make it do the function u want every time u make a change
<select
var list = document.getElementById("list");
var flag = true ;
list.onchange = function () {
if(flag){
document.bgColor ="red";
flag = false;
}else{
document.bgColor ="green";
flag = true;
}
}
<select id="list">
<option>op1</option>
<option>op2</option>
<option>op3</option>
</select>
This may not directly answer your question, but this problem could be solved by simple design level adjustments. I understand this may not be 100% applicable to all use-cases, but I strongly urge you to consider re-thinking your user flow of your application and if the following design suggestion can be implemented.
I decided to do something simple than hacking alternatives for onChange() using other events that were not really meant for this purpose (blur, click, etc.)
The way I solved it:
Simply pre-pend a placeholder option tag such as select that has no value to it.
So, instead of just using the following structure, which requires hack-y alternatives:
<select>
<option>A</option>
<option>B</option>
<option>C</option>
</select>
Consider using this:
<select>
<option selected="selected">Select...</option>
<option>A</option>
<option>B</option>
<option>C</option>
</select>
So, this way, your code is a LOT more simplified and the onChange will work as expected, every time the user decides to select something other than the default value. You could even add the disabled attribute to the first option if you don't want them to select it again and force them to select something from the options, thus triggering an onChange() fire.
At the time of this answer, I'm writing a complex Vue application and I found that this design choice has simplified my code a lot. I spent hours on this problem before I settled down with this solution and I didn't have to re-write a lot of my code. However, if I went with the hacky alternatives, I would have needed to account for the edge cases, to prevent double firing of ajax requests, etc. This also doesn't mess up the default browser behaviour as a nice bonus (tested on mobile browsers as well).
Sometimes, you just need to take a step back and think about the big picture for the simplest solution.
Add an extra option as the first, like the header of a column, which will be the default value of the dropdown button before click it and reset at the end of doSomething(), so when choose A/B/C, the onchange event always trigs, when the selection is State, do nothing and return. onclick is very unstable as many people mentioned before. So all we need to do is to make an initial button label which is different as your true options so the onchange will work on any option.
<select id="btnState" onchange="doSomething(this)">
<option value="State" selected="selected">State</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
function doSomething(obj)
{
var btnValue = obj.options[obj.selectedIndex].value;
if (btnValue == "State")
{
//do nothing
return;
}
// Do your thing here
// reset
obj.selectedIndex = 0;
}
Actually, the onclick events will NOT fire when the user uses the keyboard to change the selection in the select control. You might have to use a combination of onChange and onClick to get the behavior you're looking for.
The wonderful thing about the select tag (in this scenario) is that it will grab its value from the option tags.
Try:
<select onChange="javascript:doSomething(this.value);">
<option value="A">A</option>
<option value="B">B</option>
<option value="Foo">C</option>
</select>
Worked decent for me.
2022 VANILLA JAVASCRIPT
...because this is a top hit on Google.
Original Poster did NOT ask for a JQuery solution, yet all answers ONLY demonstrate JQuery or inline SELECT tag event.
Use an event listener with the 'change' event.
const selectDropdown = document.querySelector('select');
selectDropdown.addEventListener('change', function (e) { /* your code */ });
... or call a seperate function:
function yourFunc(e) { /* your code here */ }
const selectDropdown = document.querySelector('select');
selectDropdown.addEventListener('change', yourFunc);
What I did when faced with a similar Problem is I added an 'onFocus' to the select box which appends a new generic option ('select an option'or something similar) and default it as the selected option.
So my goal was to be able to select the same value multiple times which essentially overwrites the the onchange() function and turn it into a useful onclick() method.
Based on the suggestions above I came up with this which works for me.
<select name="ab" id="hi" onchange="if (typeof(this.selectedIndex) != undefined) {alert($('#hi').val()); this.blur();}" onfocus="this.selectedIndex = -1;">
<option value="-1">--</option>
<option value="1">option 1</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
</select>
http://jsfiddle.net/dR9tH/19/
Kindly note that Event Handlers are not supported for the OPTION tag on IE, with a quick thinking..I came up with this solution, try it and give me your feedback:
<script>
var flag = true;
function resetIndex(selObj) {
if(flag) selObj.selectedIndex = -1;
flag = true;
}
function doSomething(selObj) {
alert(selObj.value)
flag = false;
}
</script>
<select onchange="doSomething(this)" onclick="resetIndex(this)">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
What I'm doing here actually is resetting the select index so that the onchange event will be triggered always, true that you we lose the selected item when you click and it maybe annoying if your list is long, but it may help you in someway..
use jquery:
<select class="target">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<script>
$('.target').change(function() { doSomething(); });
</script>
Here's my solution, completely different to any else on here. It uses the mouse position to figure out if an option was clicked as oppose to clicking on the select box to open the dropdown. It makes use of the event.screenY position as this is the only reliable cross browser variable. A hover event has to be attached first so it can figure out the controls position relative to the screen before the click event.
var select = $("select");
var screenDif = 0;
select.bind("hover", function (e) {
screenDif = e.screenY - e.clientY;
});
select.bind("click", function (e) {
var element = $(e.target);
var eventHorizon = screenDif + element.offset().top + element.height() - $(window).scrollTop();
if (e.screenY > eventHorizon)
alert("option clicked");
});
Here is my jsFiddle
http://jsfiddle.net/sU7EV/4/
you should try using option:selected
$("select option:selected").click(doSomething);
What works for me:
<select id='myID' onchange='doSomething();'>
<option value='0' selected> Select Option </option>
<option value='1' onclick='if (!document.getElementById("myID").onchange()) doSomething();' > A </option>
<option value='2' onclick='if (!document.getElementById("myID").onchange()) doSomething();' > B </option>
</select>
In that way, onchange calls 'doSomething()' when the option changes, and
onclick calls 'doSomething()' when onchange event is false, in other words, when you select the same option
Try this (event triggered exactly when you select option, without option changing):
$("select").mouseup(function() {
var open = $(this).data("isopen");
if(open) {
alert('selected');
}
$(this).data("isopen", !open);
});
http://jsbin.com/dowoloka/4
The one True answer is to not use the select field (if you need to do something when you re-select same answer.)
Create a dropdown menu with conventional div, button, show/hide menu. Link: https://www.w3schools.com/howto/howto_js_dropdown.asp
Could have been avoided had one been able to add event listeners to options. If there had been an onSelect listener for select element. And if clicking on the select field didn't aggravatingly fire off mousedown, mouseup, and click all at the same time on mousedown.
<script>
function abc(selectedguy) {
alert(selectedguy);
}
</script>
<select onchange="abc(this.selectedIndex);">
<option>option one</option>
<option>option two</option>
</select>
Here you have the index returned, and in the js code you can use this return with one switch or anything you want.
Try this:
<select id="nameSelect" onfocus="javascript:document.getElementById('nameSelect').selectedIndex=-1;" onchange="doSomething(this);">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
A long while ago now but in reply to the original question, would this help ?
Just put onClick into the SELECT line.
Then put what you want each OPTION to do in the OPTION lines.
ie:
<SELECT name="your name" onClick>
<option value ="Kilometres" onClick="YourFunction()">Kilometres
-------
-------
</SELECT>
<select name="test[]"
onchange="if(this.selectedIndex < 1){this.options[this.selectedIndex].selected = !1}">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
I had faced a similar need and ended up writing a angularjs directive for the same -
guthub link - angular select
Used element[0].blur(); to remove the focus off the select tag. Logic is to trigger this blur on second click of the dropdown.
as-select gets triggered even when user selects the same value in the dropdown.
DEMO - link
There are a few things you want to do here to make sure it remembers older values and triggers an onchange event even if the same option is selected again.
The first thing you want is a regular onChange event:
$("#selectbox").on("change", function(){
console.log($(this).val());
doSomething();
});
To have the onChange event trigger even when the same option is selected again, you can unset selected option when the dropdown receives focus by setting it to an invalid value. But you also want to store the previously selected value to restore it in case the user does not select any new option:
prev_select_option = ""; //some kind of global var
$("#selectbox").on("focus", function(){
prev_select_option = $(this).val(); //store currently selected value
$(this).val("unknown"); //set to an invalid value
});
The above code will allow you to trigger onchange even if the same value is selected. However, if the user clicks outside the select box, you want to restore the previous value. We do it on onBlur:
$("#selectbox").on("blur", function(){
if ($(this).val() == null) {
//because we previously set an invalid value
//and user did not select any option
$(this).val(prev_select_option);
}
});

Categories