Playing with selects and javascript - javascript

My code is:
<select name='main'>
<option>Animals</option>
<option>Food</option>
<option>Cars</option>
</select>
<select name='other'>
<option>Rats</option>
<option>Cats</option>
<option>Oranges</option>
<option>Audi</option>
</select>
How can I filter my second <select>, so it would only show items which I want eg. if I choose Animals, my select would be:
<select name='other'>
<option>Rats</option>
<option>Cats</option>
</select>
and if I choose "Food", my <select> would look like:
<select name='other'>
<option>Oranges</option>
</select>
Well, I hope you get the idea. Thanks.

You'd need to create some kind of association between the selects, I'd recommend using the data-* attribute:
<select id="main_select" name='main'>
<option>Animals</option>
<option>Food</option>
<option>Cars</option>
</select>
<select id="other_select" name='other'>
<option data-category="Animals">Rats</option>
<option data-category="Animals">Cats</option>
<option data-category="Food">Oranges</option>
<option data-category="Cars">Audi</option>
</select>
Once that's in place for all of the <option> elements, the JavaScript code would look something like this:
EDITED, this works:
$(function() {
var cloned = $('#other_select option').clone();
$('#main_select').change(function() {
var selectedCategory = $(':selected', this).text();
var filtered = $(cloned).filter("[data-category='" + selectedCategory + "']");
$("#other_select option").replaceWith(filtered);
});
$('#main_select').change(); //fire the event initially.
});
jsFiddle example

You could add a change event handler to the main select box that then branches on which option was selected and then dynamically adds options to the other select. The following assumes a select with id main and id other:
HTML:
<select name="main" id="main">
<option value="1">Cars</option>
<option value="2">Food</option>
<option value="3">Animals</option>
</select>
<!-- Default the other select to 'cars' -->
<select name="other" id="other">
<option value="Audi">Audi</option>
</select>
JavaScript:
$("#main").bind("change", function() {
var categories = $("#other").get(0);
categories.options.length = 0;
switch (this.value) {
case "1":
categories.options[0] = new Option("Audi", "Audi");
break;
case "2":
categories.options[0] = new Option("Oranges", "Oranges");
break;
case "3":
categories.options[0] = new Option("Rats", "Rats");
categories.options[1] = new Option("Cats", "Cats");
break;
}
});
Check out an example here: http://jsfiddle.net/andrewwhitaker/nRGC9/

The naive solution would be:
$('select [name=main]').change(function(){
var other = $('select [name=other] option');
switch($(this).val()){
case 'Animals':
other.each(function () { if (!isAnimal($(this).val()))
$(this).hide();
else
$(this).show();
});
//where isAnimal is a function that accepts a string parameter and checks whether its an animal or not
break;
case 'food':
//continue in the same manner......
}});

Related

how to select option inside select element with javascript

So I have a select element with four options.
I want to select different options so that different functions can fire , but the onclick method is not working.
let select = document.getElementById('pbvalue');
select.addEventListener('click', dodo);
function dodo(e) {
if (e.target.value == 1) {
alert('hi')
} else {
alert('no')
}
}
<select id="pbvalue" tabindex="4">
<option value="0">""</option>
<option value="1">100</option>
<option value="2">200</option>
<option value="3">300</option>
</select>
how to select different options, so different functions can fire according to that.
Do this:
let select = document.getElementById('pbvalue');
select.onchange = function () {
// get the selected option
var value = select.options[select.selectedIndex].value
}
// get all options:
for ( int i = 0; i < select.options.length; i++ ) {
console.log( select.options[i].value )
}
This should give you an idea of how to proceed.
use onchange event.
<select id="pbvalue" tabindex="4" onchange="dodo(event)">
<option value="0" disabled>choose</option>
<option value="1">100</option>
<option value="2">200</option>
<option value="3">300</option>
</select>
<script>
function dodo(e){
switch(e.target.value){
case "1":
alert(1);//do what ever you want
break;
case "2":
alert(2);
break;
case "3":
alert(3);
break;
default:
alert("default");
break;
}
}
</script>
You can add onChange event on the select element.
<script>
function onSelectChange() {
const element = document.getElementById('pbvalue');
console.log('Selected Index: ', element.selectedIndex);
console.log('Selected Value: ', element.value);
}
</script>
<select id="pbvalue" tabindex="4" onchange="onSelectChange()">
<option value="0">""</option>
<option value="1">100</option>
<option value="2">200</option>
<option value="3">300</option>
</select>

addEventListener callback not working after createElement (only in chrome) [duplicate]

Is there a way to execute a javascript function when the user clicks on a certain <option> within a <select> drop down menu?
<select> elements support the onchange event.
http://w3schools.com/jsref/event_onchange.asp
You HTML would look like this:
<select onchange="functionName(this.value)">
<option value="1"> 1 </option>
<option value="2"> 2 </option>
<option value="3"> 3 </option>
</select>​
In your JavaScript, you would have a function ( ex: functionName() )
and you would use that function to test for each case.
Here:
elem.onclick = function ( e ) {
if ( e.target.tagName.toLowerCase() === 'option' ) {
// an <option> element was clicked
// do your thing
}
};
where elem is your SELECT element.
Live demo: http://jsfiddle.net/vBB7a/
You can use the change event to check which option the user clicked on and then execute your desired code.
In Jquery:
$('#yourSelect').change(function(){
var item = $(this).val();
if (item === "Specified Choice")
{
//do your stuff here
}
});
You need to hook the onchange event of the <select> element, and check the value. Have you tried that?
Inside your <option> you could use the onclick event to specify a javascript function to be executed.
E.g.
<option onclick="yourFunction()">
Use Jquery in your Project..
HTML Code:
<select id="myselect">
<option value="">Select</option>
<option value="1">StactOverFlow</option>
<option value="2">SuperUser</option>
<option value="3">Another 1</option>
<option value="4">Another 2</option>
<option value="5">Another 3</option>
</select>
JQuery Code:
$("#myselect").bind('change', function(){
switch($(this).val()){
case "1":
click_action_1();
break;
case "2":
click_action_2();
break;
case "3":
click_action_3();
break;
}
});
function click_action_1(){
alert('Hi 1');
}
function click_action_2(){
alert('Hi 2');
}
function click_action_3(){
alert('Hi 3');
}
​
You can even execute a new javascript function with a <option>
Watch in Action: http://jsfiddle.net/extremerose71/PnfCk/8/
Enjoy!...

Trigger a javascript function after select multiple option from <select> tag

I have a multi select tag is here. I like to call a function after select multiple option from select tag.
<select name="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
If any body mark as duplicate please let me know the correct link. I search lots here and google also. but non of solution is good for my problem.
You can listen to change event in the same way as you do this with non-multiple select:
$("#cars").on('change', function()
{
var selectedItems = $(this).find("option:selected");
if (selectedItems.length <= 1)
{
$("#result").text("not multiple!");
return;
}
var text = "";
$.each(selectedItems, function() {
text += $(this).val() + " ";
});
$("#result").text(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="cars" name="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<div id="result"></div>
Use .change instead like so :
$('select').change(function(e){
var length = $('option:selected', this).length;
if ( length > 1 ) {
alert('hey');
}
});
DEMO
You can do something like this with help of change() and blur() event handler
$('select').change(function() {
if ($('option:selected', this).length > 1) {
// set custom data attribute value as 1 when change event occurred and selected options are greater than 1
$(this).data('select', 1);
} else
//set value as zero in other case
$(this).data('select', 0);
}).blur(function() {
if ($(this).data('select')) {
// when focus out check custom attribute value
alert('selected more than one');
// code here
// call your function here
}
$(this).data('select', 0)
// set custom attribute value to 0
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
try this, it will call a function passing the newly selected value into functionToCall.
var values = [];
$('select').change(function(e){
var current = $(this).find('option:selected').map(function() {
return $(this).val();
});
var newValue = $(current).not(values).get();
values = current;
if(newValue.length)
functionToCall(newValue);
});
function functionToCall(value){
alert(value);
console.log(value);
}
Fiddle

How to establish relationship between option tag of different select tags in html

I have three select tags in HTML with option tag.I want to establish relationship between option tags of different select tag.
EDIT-1
When I choose Reference-1 from select name="reference" then 2014-10-10 07:17:00 and 2014-10-10 08:46:00 from select name="from" and select name="to" should only be present in the dropdown list.When I choose Reference-2 then 2014-09-01 10:00:00 and 2014-09-01 11:00:00 should only be present in dropdown list of from and to select tag. My html code for is-
<form method="post">
Select Reference:
<select name="reference">
<option value="Select">Select</option>
<option value="Reference-1">Reference-1;</option>
<option value="Reference-2">Reference-2</option>
<option value="Reference-3">Reference-3</option>
<option value="Reference-4">Reference-4</option>
</select>
From Date:
<select name="from">
<option value="Select">Select</option>
<option value="2014-10-10 07:17:00">2014-10-10 07:17:00</option>
<option value="2014-09-01 10:00:00">2014-09-01 10:00:00</option>
<option value="2014-09-08 10:00:00">2014-09-08 10:00:00</option>
</select>
To Date:
<select name="to">
<option value="Select">Select</option>
<option value="2014-10-10 08:46:00">2014-10-10 08:46:00</option>
<option value="2014-09-01 11:00:00">2014-09-01 11:00:00</option>
<option value="2014-09-08 10:00:00">2014-09-08 11:00:00</option>
</select><br>
<b>Select Date to be compared</b>
<p>Date: <input type="text" id="datepicker"></p>
<input type="submit" value="Submit"><br>
</form>
Get the index of the selected option from reference select element and then disable all the options of from and to select elements except the option with index of the previous index you got from reference select option.
javaScript Solution :
var reference = document.getElementsByName("reference")[0];
var fromSelect = document.getElementsByName("from")[0];
var toSelect = document.getElementsByName("to")[0];
reference.onchange = function(){
var selectedIndex = this.selectedIndex;
for(var i = 1; i <= fromSelect.length; i++){
if(i != selectedIndex){
fromSelect.getElementsByTagName("option")[i].disabled = true;
toSelect.getElementsByTagName("option")[i].disabled = true;
} else{
fromSelect.getElementsByTagName("option")[i].disabled = false;
toSelect.getElementsByTagName("option")[i].disabled = false;
}
}
};
jsFiddle
jQuery Solution :
$("select[name='reference']").on("change", function(){
var $fromSelect = $("select[name='from']");
var $toSelect = $("select[name='to']");
var selectedIndex = $(this).children("option:selected").index();
$fromSelect.children("option").removeAttr("disabled");
$toSelect.children("option").removeAttr("disabled");
$fromSelect.children("option").not(":eq(" + selectedIndex +")").prop("disabled", "disabled");
$toSelect.children("option").not(":eq(" + selectedIndex +")").prop("disabled", "disabled");
});
jsFiddle
If second selection values are dependent on the first selection option, then you should disable the whole second selection until the first one is selected.
When the first one is selected then disable all the unrelated options in second selection and make it enabled to the user. Let me know if it helped.
$("select[name='reference']").on('change', function() {
var value = $(this).val(); // first selection value
if ("Reference-1" == value ) {
var $selection2 = $("select[name='from']");
$selection2.find("option[value*='2014-09-01 10:00:00']").prop('disabled',true);
$selection2.find("option[value*='2014-09-08 10:00:00']").prop('disabled',true);
}
...
});
Here is DEMO

How to run a piece of javascript when you select a dropdown option?

I have a select with loads of options. (Code below shortened for sake of example).
I want it to set the value of the input textfield "hoh" to "10" when you click/select all dropdown options, except one, that should set it to 50.
I imagined something like this would work, but its not. What am I doing wrong here?
<select>
<option onselect="document.getElementById('hoh').value = '50'">Hey</option>
<option onselect="document.getElementById('hoh').value = '10'">Ho</option>
<option onselect="document.getElementById('hoh').value = '10'">Lo</option>
....
</select>
<input type="text" id="hoh" value="10">
Something like this should work:
<script>
function myFunc(val) {
if (val == '50') {
document.getElementById('hoh').value = val;
} else {
document.getElementById('hoh').value = '10';
}
}
</script>
<select onchange="myFunc(this.value)">
<option value="1">one</option>
<option value="2">two</option>
<option value="50">fifty</option>
</select>
http://jsfiddle.net/isherwood/LH57d/3
The onselect event refers to selecting (or highlighting) text. To trigger an action when a dropbox selection changes, use the onchange event trigger for the <select> element.
E.g. Since you didn't already set the value attribute of your option tags.
<select id="myselect" onchange="myFunction()">
<option value="50">Hey</option>
<option value="10">Ho</option>
<option value="10">Lo</option>
....
</select>
and somewhere inside of a <script> tag (presumably in your HTML header) you define your javascript function.
<script type="text/javascript>
function myFunction() {
var dropbox = document.getElementById('myselect');
document.getElementById('hoh').value = dropbox[dropbox.selectedIndex].value;
}
</script>
I'm not sure it's wise to repeat the same value among different options in a droplist, but you could expand on this to implement the result other ways, such as if the sole option which will have value 50 is in a certain position, you could compare the selectedIndex to that position.
you could add an onchange event trigger to the select, and use the value of an option to show in the textbox
see http://jsfiddle.net/Icepickle/5g5pg/ here
<select onchange="setValue(this, 'hoh')">
<option>-- select --</option>
<option value="10">Test</option>
<option value="50">Test 2</option>
</select>
<input type="text" id="hoh" />
with function setValue as
function setValue(source, target) {
var tg = document.getElementById(target);
if (!tg) {
alert('No target element found');
return;
}
if (source.selectedIndex <= 0) {
tg.value = '';
return;
}
var opt = source.options[source.selectedIndex];
tg.value = opt.value;
}
Try this code
var inp = document.getElementById('hoh');
sel.onchange = function(){
var v = this.value;
if( v !== '50'){
v = '10';
}
inp.value = v;
};

Categories