Using numeric values to select item from a dropdown box with JavaScript - javascript

I have a multitude of dropdown boxes within my web page. One of these dropdown boxes is used for a single selected value out of a list of options.
<SELECT id="Box0" name="">
<OPTION value="1920">my weird description</OPTION>
<OPTION value="1225">other weird description</OPTION>
<OPTION value="3112">some name dynamically fetched</OPTION>
</SELECT>
How can I add an event to this section, so when it is in focus, I could use numeric keys like 1,2.. to select an option instead of using the mouse or arrow keys for selecting an option? For clarification: if I press 1 on my keyboard, the selected value would become the first value from that list, with 2 the selected value becomes second value from that list.
I choose not to use a library/framework such as JQuery/Mootools.

You could put a 'rel' attribute on each option which would be the required key for selecting that option. So, for your example it could be:
<select id="Box0" name="">
<option value="0" rel="0">None</option>
<option value="1" rel="1">First</option>
<option value="2" rel="2">Second</option>
<option value="3" rel="x">Millionth</option>
</select>
You wouldn't be looking for the onfocus() event though, you would be looking for the onkeydown() (or similar) event on the select box, which could look something like this:
var MySelect = document.getElementById('Box0');
var MyOptions = MySelect.getElementsByTagName('option');
var KeyPressed = //detect which key has been pressed. I can't remember the
//specific code for this off the top of my head
for (i=0; i<MyOptions.length; ++i) {
if (MyOptions[i].rel == KeyPressed) {
MyOptions[i].selected = true;
} else {
MyOptions[i].selected = false;
}
}

If you have less than 10 options, simply add the number to the text:
<option value="0">0 none</option>
<option value="1">1 first</option>
<option value="2">2 second</option>
or perhaps easier to read:
<option value="0">0 none</option>
<option value="1">1st</option>
<option value="2">2nd</option>
No other coding necessary

I think this can solve your problem
<html>
<head>
<script type="text/javascript">
function selectvalue(e){
e = e || event;
var key = e.which || e.keyCode;
if(!e.shiftKey && key >= 48 && key <= 57){
var option = this.options[key - 48];
if(option){
option.selected = "selected";
}
}
}
</script>
</head>
<body>
<SELECT id="Box0" name="" onkeypress="selectvalue.apply(this, arguments)">
<OPTION value="1920">my weird description</OPTION>
<OPTION value="1225">other weird description</OPTION>
<OPTION value="3112">some name dynamically fetched</OPTION>
</SELECT>
</body>
</html>
The javascript looks little messy because it has to handle IE and all other browsers.
IE does not pass an event object to the handler function instead we have to use the global event object.
Same way the keycode also is stored in keyCode instead of which in IE.

Related

How do you pass a value to a hidden form field when a certain option is selected?

I am new to javascript and cannot find an easy-to-understand answer.
I would like a certain value to get passed to a hidden field when a user selects a certain option from the select dropdown.
I know that there are if/else statements but I'm not sure if that would be used in this situation.
For example: I have a select dropdown of a list of states.
<select name="HomeState" required>
<option value="1">Alabama</option>
<option value="1">Alaska</option>
<option value="1">Arizona</option>
<option value="1">Arkansas</option>
<option value="5">California</option>
<option value="1">Colorado</option>
<option value="1">Connecticut</option>
<option value="1">Delaware</option>
</select>
As you can see, any option other than California will be rated at a value of 1.
I would like it to where if the user selects the option of California, then the value of $300 will get passed to a hidden form field.
<input name="AmountNeeded" type="hidden" value="300" />
If they select anything other than California, the hidden field would get passed $100
<input name="AmountNeeded" type="hidden" value="100" />
How would I implement this logic? Would it be using if/else statement? I am new and don't exactly know how to set that up.
To keep this simple you could assign ids to the <select> and hidden <input> and listen to the change event via onchange() on the <select> with a function call.
And based on the selected item, change the value of hidden input.
NOTE: To test the snippet out I have removed the type="hidden". Do place it back.
function homeSelected(){
const home = document.getElementById("homeSelector").value;
if(home == 5){
document.getElementById("amountNeeded").value = 300;
}else{
document.getElementById("amountNeeded").value = 100;
}
}
<select id="homeSelector" name="HomeState" onchange="homeSelected()" required>
<option value="1">Alabama</option>
<option value="1">Alaska</option>
<option value="1">Arizona</option>
<option value="1">Arkansas</option>
<option value="5">California</option>
<option value="1">Colorado</option>
<option value="1">Connecticut</option>
<option value="1">Delaware</option>
</select>
<input id="amountNeeded" name="AmountNeeded" value="100" />
You can do this as follows:
<select name="HomeState" required onChange=myFunction(this)>
<option value="1">Alabama</option>
<option value="1">Alaska</option>
<option value="1">Arizona</option>
<option value="1">Arkansas</option>
<option value="5">California</option>
<option value="1">Colorado</option>
<option value="1">Connecticut</option>
<option value="1">Delaware</option>
</select>
Javascript code is:
<script>
function myFunction(x) {
val = x.options[x.selectedIndex].text;
if(val == 'California')
document.getElementsByName("AmountNeeded")[0].value = 300
else
document.getElementsByName("AmountNeeded")[0].value = 100
}
</script>
If else statement is good for you if you are sure that All other states have value 1 except California. If all states may have different values like some states may have 1 or some may have 2 or some may have 3, then there may be other alternatives to solve this like you can pass give one more attribute data-src-amount to options and give amount to data-src-amount. You can create options like <option value="1" data-src-amount="100">Alabama</option> and in script, you can fetch data-src-amount on select change event instead of if-else statement.

Wait for all the select lists to load jQuery

I have two select lists and the second one depends on the first. I would like to allow the second select list to load and then fire some alerts after that. What is the best way to achieve this using jQuery?
For eg: The second list gets populated in the following manner below:
1 - a,b,c
2 - b,c,d
3 - a,c,d
4 - a,b
Meaning that if someone selects 1 in the first picklist, the second one is loaded with options a,b,c.
$("#first").change(function() { // bind a change event:
refreshsecond(document.theForm);
}).change(); // and trigger a "change" event immediately
function refreshsecond(form)
{
var length = $('#second').children('option').length;
alert("Length is :" + length);
}
<select id="first" name="firstName">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
</select>
<select id="second" name="secondName">
<option value='a'>a</option>
<option value='b'>b</option>
<option value='c'>c</option>
<option value='d'>d</option>
</select>
Other than having #second load elements in a certain way a better idea is to just add and replace to the elements HTML. Meaning that we start with #second being empty and change the <option> items based on the first select box's value. For example:
$("#first").change(function() {
if($(this).val() == 1)
$("#second").html(loadValues(['a','b','c']));
else if($(this).val() == 2)
$("#second").html(loadValues(['b','c','d']));
else if($(this).val() == 3)
$("#second").html(loadValues(['a','c','d']));
else if($(this).val() == 4)
$("#second").html(loadValues(['a','b']));
var length = $('#second').children('option').length;
alert("Length is :" + length);
}).change();
function loadValues(ArrValues){
var string = "";
for(var i = 0; i < ArrValues.length; i++)
string += "<option value='"+ArrValues[i]+"'>"+ArrValues[i]+"</option>";
return string;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="first" name="firstName">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
</select>
<select id="second" name="secondName">
</select>
If it's dependent on the user selecting one in the first dropdown, you simply need to attach an onChange handler to the first dropdown list.
For example
$('#first').change(function() {
//do your stuff here to second dropdown list.
});
Take a look at http://api.jquery.com/change/ for more details.

onchange not working for drop down menu?

I'm trying to make it so that when a selection is made from my dropdown menu, text will display accordingly inside my textarea, for now I've been trying to just get one of them to work.
PROBLEM: It won't display the string from the array inside the textarea. Is the problem within this code?
The drop down menu:
<select id="dropdown" onchange="getFrames();">
<option value="1" selected="selected"> Blank </option>
<option value="2"> Exercise </option>
<option value="3"> Juggler </option>
<option value="4"> Bike </option>
<option value="5"> Dive </option>
</select>
The textarea :
<textarea id="textstage" rows="80" cols="20"> </textarea>
JavaScript :
I have these global variables.
var theStage = document.getElementById("textstage");
var getDrop = document.getElementById("dropdown");
and then I have this function.
function getFrames(){
var dropSel = getDrop.options[getDrop.selectedIndex].value;
if(dropSel === 2){
theStage.value = ANIMATIONS["Exercise"];
}
The array being referenced is a global array from another js file.
Try:
var theStage,getDrop;
function getFrames() {
var dropSel = getDrop.options[getDrop.selectedIndex].innerHTML;//+getDrop.value;
theStage.value = ANIMATIONS[dropSel];
}
//Place the selection part on load callback
window.onload = function () {
theStage = document.getElementById("textstage");
getDrop = document.getElementById("dropdown");
}
Demo
You can just use getDrop.value instead of doing getDrop.options[getDrop.selectedIndex].value.
=== is strict equality comparison meaning "2" === 2 will be false as in your case.
Seems like you are looking for the option text to look up the value based on this as key in your object Animation. So you can just do getDrop.options[getDrop.selectedIndex].innerHTML
Your document selection code should be inside window.onload or after the element in the html
I made a minor change to your html by omitting the inline event handler, and instead added it to the javascript.
html:
<select id="dropdown">
<option value="1" selected="selected"> Blank </option>
<option value="2"> Exercise </option>
<option value="3"> Juggler </option>
<option value="4"> Bike </option>
<option value="5"> Dive </option>
</select>
<textarea id="textstage" rows="80" cols="20"> </textarea>
Also, in the javascript, I took away the strict equality (===) and made it just (==).
javascript:
var theStage = document.getElementById("textstage");
var getDrop = document.getElementById("dropdown");
getDrop.addEventListener("change",getFrames);
function getFrames(){
var dropSel = getDrop.options[getDrop.selectedIndex].value;
if(dropSel == 2){
theStage.value = ANIMATIONS["Exercise"];
}
}
Hopefully it should work now for you.

How to use document.getElementsByTagName(

I want to use this function to work on all my drop down lists. Problem: the first drop down works okay, but hen I try select any option in the 2nd drop down selections. It places the value from the first group in the span of the second group. I want the span to have the value from its own group. I would like to use this on multiple groups.
The code below does not work properly. the phone number display okay but when i try to select the parts, the value of the phone number is displayed, no matter what the selection is.
I want the phone number when i select phones, and parts when i select parts.
Thank you
<script>function displayResult(xspan,xselect)
{
var x=document.getElementById(xselect).selectedIndex;
alert(x);
var newTxt = document.getElementsByTagName("option")[x].value;
document.getElementById(xspan).innerHTML = newTxt;
//alert(document.getElementsByTagName("option").length);
}
</script>
<select id="myPhones" onchange="displayResult('ShowPhone','myPhones')">
<option value="">Phone Numbers</option>
<optgroup label="Shipping">
<option value=" - 800-463-3339">FedEx</option>
<option value=""></option>
</optgroup>
</select>
<span id="ShowPhone"></span>
<select id="myParts" onchange="displayResult('ShowParts','myParts')">
<option value="">Qik Parts list</option>
<optgroup label="BATT">
<option value="1">1</option>
<option value="2">1</option>
<option value="2">1</option>
<option value="2"><1/option>
</optgroup>
</select>
<span id="ShowParts"></span>
Mostly comments:
When you do:
var newTxt = document.getElementsByTagName("option")[x].value;
then document.getElementsByTagName("option") returns all the options in the document, you probably only want the ones for the select in question. But the options for a select are available as a collection, so you can do:
selectElement.options[x].value;
But that is unnecessary unless you are dealing with very old browsers or IE where there are no value attributes. Just use selectElement.value.
Where you have:
<select id="myPhones" onchange="displayResult('ShowPhone','myPhones')">
you can instead do:
<select id="myPhones" onchange="displayResult('ShowPhone', this.value)">
so that you pass the current value of the select directly to the function. Then the function can be:
function displayResult(id, value) {
document.getElementById(id).innerHTML = value;
}
This should work, though I haven't tested it.
function displayResult(spanId, selectId) {
document.getElementById(spanId).innerHTML = document.getElementById(selectId).value;
}

How to stdout selected value in JavaScript?

Suposse user hits SPACE in a text -field. I want to check the value in the select -box. I use input.addEventListener('keydown', function(e)... to track the SPACE-hitting-point but how can I get the value of the select block <select id='topic'><option value="hello"></option> ...</section>?
How can you stdout the value of the selected index? Cannot understand why not below.
var el = document.getElementById("topic");
var topicValue = el.options[el.selectedIndex].value;
// PROBLEM: Won't do anything (despite inside <script> -tags)
window.alert(topicValue);
where the topic is the select <select id="topic"[^>]*>[^<]*</select>.
There any many events you can look at.
This has a list of them all
http://www.w3schools.com/tags/tag_select.asp
onkeydown and onmousedown will alert you prior to the onchange (user pressing enter) event
The events work in the select, not to options but just conditional to the script.
<html>
<body>
<script>
function alertMe(option){
if(option == "saab"){
window.alert("you clicked saab in selec!");
document.getElementById("txt").value='saab!';
}
}
</script>
<select onChange="alertMe(this.value);">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="m"> Mercedes</option>
<option>Audi</option>
</select>
<input type="text" id="txt" value="change me"></input>
</body>
</html>
[Answers to the updated]
You can access the select with document.getElementById('topic').options.selectedIndex or mySelect.options[selectedIndex].value (does not work with me). And apparently you could create a form to which you could refer by document.forms['topic'].elements[id] but not sure about this one. More.
#Kosh that is irritating! Just do a dictionary = {0:"topic", 1:"hello",...,n:"topic_{n}"} and then use the getElementById('topic').selectedId as a key and forget the values. Not solved but rounded.
[Update] I think I solved it, just el.value, no selectedIndex needed:
<html>
<body>
<script>
function printSelectValue()
{
var el = document.getElementById("selectOne");
alert(el.value);
}
</script>
<select id="selectOne" onChange="printSelectValue()">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="m"> Mercedes</option>
</select>
</body>
</html>

Categories