onchange not working for drop down menu? - javascript

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.

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.

javascript to dynamically change the dropdown

Attached the screenshot of my web page.
In that picture, under Regression type dropdown list box, there are three values consider 1, 2 and 3
So if I select 1 or 2, drop down below that "F1" should not appear. If value3, then it should appear.
To do this I have added onload under body tag.
HTML CODE:
<div class = "cl-regr" id="div-regr">
<select name = "regr" id="drop-regr">
<option selected="selected" disabled>-----Select-----</option>
<option value = "1"> ips </option>
<option value = "2"> ips sanity </option>
<option value = "3"> Features </option>
</select>
</div>
<div class = "cl-ftr" id="div-ftr" onchange="displayFeatureList()">
<select name = "ftr" class = "cl2" id="drop-ftr">
<option value = "f1"> F1 </option>
<option value = "f2"> F2 </option>
<option value = "f3"> F3 </option>
<option value = "f4"> F4 </option>
</select>
</div>
RESPECTIVE SCRIPT IN SEPARATE .js FILE:
function func1(){
$(".cl-ftr").each(function() {
var that = $(this);
that.find("div.cl2").style.visibility="hidden";
});
};
function displayFeatureList(){
var d_obj = document.getElementById("drop_reg").value;
var op = d_obj.options[d_obj.selectedIndex].value;
if (op == 3){
document.getElementById("drop_ftr").style.visibility = 'visible';
}
else{
document.getElementById("drop_ftr").style.visibility = 'hidden';
}
};
where I'm calling func1 from body tag
<body onload="func1()">
Problems I'm facing are,
1)Whenever the page loads, the "F1" dropdown list box of first row is hiding (ie, ClientIP - 10.213.174.90)
2) If I change the value, displayFeatureList function is not making any effects.
Any help would be much appreciated!!
you are syntax was wrong
$(this) is jquery object style.visiblity its dom function
Use with css() jquery function .style.visiblity is not a jquery object.
For better my suggestion use css .cl2{visiblity:hidden} instead of js
cl2 class in select element not with div so remove the div with cl2 in selector like find('cl2')
fix the id name typo - instead of _
Add change event with first select
Get the value from dropdown direct call the selectelement.value.no need specify index
function func1() {
$(".cl-ftr").each(function() {
var that = $(this);
that.find(".cl2").css('visibility', "hidden");
});
};
function displayFeatureList() {
var d_obj = document.getElementById("drop-regr").value
if (d_obj == '3') {
document.getElementById("drop-ftr").style.visibility = 'visible';
} else {
document.getElementById("drop-ftr").style.visibility = 'hidden';
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onload="func1()">
<div class="cl-regr" id="div-regr">
<select name="regr" id="drop-regr" onchange="displayFeatureList()">
<option selected="selected" disabled>-----Select-----</option>
<option value = "1"> ips </option>
<option value = "2"> ips sanity </option>
<option value = "3"> Features </option>
</select>
</div>
<div class="cl-ftr" id="div-ftr" >
<select name="ftr" class="cl2" id="drop-ftr">
<option value = "f1"> F1 </option>
<option value = "f2"> F2 </option>
<option value = "f3"> F3 </option>
<option value = "f4"> F4 </option>
</select>
</div>
With all respect, your code quality is not very good.
It's filled with typos (changing _ to -, missing single letters for ids etc.) This way, nothing will ever work. Take more care.
An id has to be unique. If an id appears twice in the same HTML document,
the document is not valid by definition. (It still loads though, but you have to expect errors.) You maybe want to keep the ids an add a dynamic number (row number)to keep them unique
If you use jQuery, use it by default. Don't mix up jQuery(func1()) and JS DOM methods(displayFeatureList)
I reduced your code to the following (I commented the whole JS code for better understanding):
$(document).ready(function() { //run when page loading is complete
$(".regessionTypeCell").each(function() { //for each regessionTypeCell class (parent div, might be a table cell in your case)
$(this).find(".drop-regr").change(function(event) { //set onChange function for the containing drop-regr class
var conditionalDropdown = $(this).find(".cl-ftr"); //get the conditional dropdown element
if ($(this).find(".drop-regr").val() == 3) { //if selected index is equal 3
conditionalDropdown.show(); //show dropdown
} else {
conditionalDropdown.hide(); //hide dropdown
}
}.bind($(this))); //bind this to the inner function
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="regessionTypeCell">
<div class="cl-regr">
<select name="regr" class="drop-regr">
<option selected="selected" disabled>-----Select-----</option>
<option value="1"> ips </option>
<option value="2"> ips sanity </option>
<option value="3"> Features </option>
</select>
</div>
<div class="cl-ftr" style="display:none">
<select name="ftr" class="drop-ftr">
<option value="f1"> F1 </option>
<option value="f2"> F2 </option>
<option value="f3"> F3 </option>
<option value="f4"> F4 </option>
</select>
</div>
</div>
<div class="regessionTypeCell">
<div class="cl-regr">
<select name="regr" class="drop-regr">
<option selected="selected" disabled>-----Select-----</option>
<option value="1"> ips </option>
<option value="2"> ips sanity </option>
<option value="3"> Features </option>
</select>
</div>
<div class="cl-ftr" style="display:none">
<select name="ftr" class="drop-ftr">
<option value="f1"> F1 </option>
<option value="f2"> F2 </option>
<option value="f3"> F3 </option>
<option value="f4"> F4 </option>
</select>
</div>
</div>

jQuery: Get value from multiple fields and show in text field

I have 6 different select boxes and a text field which I need to fetch the value from and combine in to one text field using jQuery.
I understand essentially I will build the value for the targetTextField with a string like this: $('#targetTextField').val(opt1+opt2+opt3+opt4+opt5+opt6+textField);
What do I use to fetch the value of select#options1 and transform that in to opt1?
Would it be along the lines of opt1 = $('select#options1').val(); or am I heading in completely the wrong direction?
I've created a basic jsfiddle with just two options at:
http://jsfiddle.net/e2ScF/2/
jQuery
$(function() {
$("#options").change(function(){
var opt1 = $('select#options').val()
}$('#targetTextField').val(opt1+opt2);
});
$("#options2").change(function(){
var opt2 = $('select#options2').val()
}$('#targetTextField').val(opt1+opt2);
});
});​
HTML
<select id="options">
<option value="" selected>Choose...</option>
<option value="opt1Value1" >Option 1</option>
<option value="opt1Value2" >Option 2</option>
</select>
<select id="options2">
<option value="" selected>Choose...</option>
<option value="opt2Value1" >Option 1</option>
<option value="opt2Value2" >Option 2</option>
</select>
<input type="text" id="targetTextField" name="targetTextField" size="31" tabindex="0" maxlength="99">​
...but it doesn't appear to be working, so I've obviously misunderstood or missed something.
I made this demo for you, hope it helps
http://jsfiddle.net/e2ScF/5/
$(function() {
$("#options").change(function(){
setTarget() ; // Something has changed so lets rebuild the target
});
$("#options2").change(function(){
setTarget();// Something has changed so lets rebuild the target
});
});
// Just get the values you want and update the target
function setTarget(){
var tmp = $("#options").val();
tmp += $("#options2").val();
$('#targetTextField').val(tmp);
}
​
for dropdown try following
$('select option:selected').text()
have a look at this it should hopefully give you a pointer in what you need to do.
you can change the name to be a class and then just provide your format you want to display in the input. but from your question in presume it should be about that.
If you have different id for select box
var toalopt=$('select option1:selected').text();
toalopt+=$('select option2:selected').text();
toalopt+=$('select option3:selected').text();
toalopt+=$('select option4:selected').text();
toalopt+=$('select option5:selected').text();
toalopt+=$('select option6:selected').text();
document.getElementById('id where you want to club data').innerHTML=toalopt;
If you have same id
$(document).ready(function(){
$('#optionvalue).click(function(){
var values ='';
$('select[name="sameid"]').each(function(index,item){
values +=$(item).val() +' ';
});
$('id where you want to club data').val(values);
});
});
HTml will be normal select tag with id.
First of all, add a class to each of your select elements to better identify them as a group:
<select id="options" class="auto-updater">
<option value="" selected>Choose...</option>
<option value="opt1Value1" >Option 1</option>
<option value="opt1Value2" >Option 2</option>
</select>
<select id="options2" class="auto-updater">
<option value="" selected>Choose...</option>
<option value="opt2Value1" >Option 1</option>
<option value="opt2Value2" >Option 2</option>
</select>
<input type="text" id="targetTextField" name="targetTextField" size="31" tabindex="0" maxlength="99">
Then in jQuery, you can use map() to create an array of the values and display them:
$(".auto-updater").change(function() {
var values = $(".auto-updater").map(function() {
return ($(this).val() == "") ? null : $(this).val(); // ignore default option select
// return $(this).val(); // include all values
}).get();
$("#targetTextField").val(values.join(','));
});
Example fiddle
You can see that I've set this up to ignore select elements which are left on their default value. If you uncomment the line beneath it will include all selects, regardless of value chosen.
Minimal code required for you as below:
$(function() {
$("select").change(function(){
var opts=$('option:selected').val();
var oldVal=$('#targetTextField').val();
$('#targetTextField').val(oldVal+opts);
});
});​
Find the jsfiddle demo here.

javascript change div based on dropdown

I have a dropdown list with 2 options:
<select name="list" size="1">
<option value=1>Option 1</option>
<option value=2>Option 2</option>
</select>
And i want to set <span id=tag></span> to display different text depending on which option is highlighted in the dropdown. How can I do this?
Well, the question is pretty vague but in general you would do something like this:
Html:
<select id="mySelect" name="list" size="1">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<span id="tag"></span>
Javascript:
//cache the select and span elements
var mySelect = document.getElementById("mySelect"),
tag = document.getElementById("tag");
//when it changes
mySelect.onchange = function() {
//change the tag innerHTML checking the selected value of the select
tag.innerHTML = mySelect.value === "1" ? "some text" : "some other text";
}
You could change the ternary operator (? :) for a few if statements, if you need more conditions.
Notice that I've added an Id to the <select>. You can avoid the caching part if you want to get the span each time the select changes for some reason
You can do it with an onchange event handler on your <select>:
<select name="list" id="list">
<option value="1">Option 1</option>
<option value="1">Option 1</option>
</select>
<span id="tag"></span>
<script>
// Get references to the objects you need (<select> and <span>)
var list = document.getElementById('list');
var tag = document.getElementById('tag');
// When the list value changes, set the innerHTML of the <span>
list.onchange = function() {
tag.innerHTML = this.value;
};
</script>
Notice in the above that I've added id attributes to both your select and span elements. This allows me to easily get a reference to them in Javascript.
It's also important for my example that the script is executed after the elements are rendered, otherwise the document.getElementById call won't return a reference to them. You could get around this limitation by moving the script into a window.onload handler.
Here's a simple example of it working.

Using numeric values to select item from a dropdown box with 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.

Categories