switch statement with Redirect - javascript

Ok here's the deal, I'm trying to have a switch statement redirect to another page depending on what option is selected in a select box. Below is a sample i'm working with and trying to figure out, any help at all would be greatly apreciated.
<html>
<body>
<form name="form1">
<select name="select1">
<option value="p1">p1</option>
<option value="p2">p2</optino>
</select>
</form>
<script type="text/javascript">
<!--
var sel = document.form1.select1;
var txt = sel.options[sel.selectedIndex].text;
var opt = sel.options[sel.selectedIndex].value;
switch (sel)
{
case 'p1': window.location = 'http://www.yahoo.com'
break;
case 'p2': window.location = 'http://www.google..com'
break;
}
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

I recommend you avoid switch-statements. How about this?
<select name="select1">
<option data-url="http://www.yahoo.com" value="p1">p1</option>
<option data-url="http://www.google.com" value="p2">p2</option>
</select>
And:
document.getElementById("select1").onchange = function () {
var url = this.options[this.selectedIndex].getAttribute("data-url");
window.location = url;
};
Edit: I changed the example to use html 5 data attributes (not to worry, they are 100% supported in all browsers), since you need the value attribute for something else.

You need to bind an event handler
Your switch was using the wrong value
See http://www.jsfiddle.net/vDFpZ/
<html>
<body>
<form name="form1">
<select name="select1">
<option value="p1">p1</option>
<option value="p2">p2</option>
</select>
</form>
<script type="text/javascript">
window.onload = function () {
document.getElementsByName("select1")[0].onchange = function () {
var sel = this.options[this.selectedIndex];
var text = sel.text;
var val = sel.value;
switch (val)
{
case 'p1': window.location = 'http://www.yahoo.com'
break;
case 'p2': window.location = 'http://www.google..com'
break;
}
}
}
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>​

i noticed that you did not bind an change handler to the select, so when the user selects a value nothing happens.

You've got some typos, your second "/option" and your "google.com".
And the switch statement has nothing to do with your error.
You have no event listener/onchange handler and you aren't switching with the value from the select option
https://developer.mozilla.org/en/DOM/element.onchange
https://developer.mozilla.org/en/DOM/element.addEventListener

Related

Getting an option value to call a javascript function

I'm trying to get an dropdown menu to call javascript functions. The option value seems to default to calling a web page, but I need it run the javascript instead. The javascript I'm using works great when using an onclick fucntion. How can I modify it so it works for my dropdown menu?
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystylesheet.css">
</head>
<body>
<form>
<p><b>Select a Staff Position </b>
<select onchange="window.open(this.value,'','');">
<option value="">Select one</option>
<option value="myFunction1()">Illustrators</option>
<option value="myFunction2()">Tech Writers</option>
</p>
</select>
</form>
<script>
var iframeExists = false;
function myFunction1() {
var x
if (!iframeExists) {
x = document.createElement("IFRAME");
iframeExists = true;
} else {
x = document.getElementsByTagName("IFRAME")[0];
}
x.setAttribute ("src", "http://www.oldgamer60.com/Project/Illustrators.php");
document.body.appendChild(x);
}
function myFunction2() {
var x;
if (!iframeExists) {
x = document.createElement("IFRAME");
iframeExists = true;
} else {
x = document.getElementsByTagName("IFRAME")[0];
}
x.setAttribute("src", "http://www.oldgamer60.com/Project/TechWriters.php");
document.body.appendChild(x);
}
</script>
<br>
</body>
</html>
DRY code makes your life much simpler.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystylesheet.css">
</head>
<body>
<form>
<p><b>Select a Staff Position </b>
<select id="mySelect" onchange="select_change()">
<option value="">Select one</option>
<option value="Illustrators">Illustrators</option>
<option value="TechWriters">Tech Writers</option>
</select>
</p>
</form>
<script>
var iframeExists = false;
function select_change() {
var my_select = document.getElementById("mySelect");
var my_select_value = my_select.options[my_select.selectedIndex].value;
var x;
if (!iframeExists) {
x = document.createElement("IFRAME");
iframeExists = true;
} else {
x = document.getElementsByTagName("IFRAME")[0];
}
if(my_select_value) {
x.setAttribute("src", "http://www.oldgamer60.com/Project/" +
my_select_value + ".php");
document.body.appendChild(x);
}
}
</script>
</body>
</html>
Not sure this is the best way to do it but it should provide a solution.
It's possible to store your functions in an object and then call them from a string using the following syntax:
object['nameOfFunction']();
So if we setup the script like so:
function callFunction(){
console.log('change');
var e = document.getElementById('select');
var value = e.options[e.selectedIndex].value;
if (value !== "") {
functions[value]();
}
}
var functions = {
myFunction1: function(){
/*function1 code*/
},
myFunction2: function(){
/*function2 code*/
}
};
So we've got an object 'functions' which has two members called 'myFunction1' and 'myFunction2'. We then have another function which pulls the value from the select and runs the selected function.
And your html like this:
<form>
<p><b>Select a Staff Position </b>
<select id="select" onchange="callFunction()">
<option value="">Select one</option>
<option value="myFunction1">Illustrators</option>
<option value="myFunction2">Tech Writers</option>
</select></p>
</form>
In the html we change the onchange to call our function selector and remove the brackets from the 'myFunction' values.
NOTE: You need to lay out your code so that the script is above the form, maybe in the header, otherwise the 'onchange=' can't access the 'callFunction' due to it not being defined.
EDIT: Take a look at the code here to see it in action: http://plnkr.co/edit/?p=preview
Your HTML mark-up is incorrect. Your </p> is misplaced.
Use this:
<form>
<p><b>Select a Staff Position </b>
<select onchange="window.open(this.value,'','');">
<option value="">Select one</option>
<option value="myFunction1()">Illustrators</option>
<option value="myFunction2()">Tech Writers</option>
</select>
</p>
</form>
Working demo (let it allow popups): https://jsbin.com/xesiyavilu/edit?html,js,output
Update 1:
The issue is that when you do <option value="myFunction1()">Illustrators</option> then myFunction1() is passed as a string.
Change your markup to:
<select onchange="popup(this.value)">
<option value="">Select one</option>
<option value="1">Illustrators</option>
<option value="2">Tech Writers</option>
</select>
in your Javascript, change myFunction1() and myFunction2() to have it return some value, then add this function:
function popup(val){
console.log('val: ' + val);
if(val === '1'){
// call myFunction1() and get something in return;
} else {
// call myFunction2() and get something in return;
}
window.open(returnedValue,'','');
}

Displaying option selected from dropdownlist

Trying something that sounds simple but not working:
Allow a user to select an option from a dropdownlist and then have this displayed as an alert each time the user changes it. Here's what I've got so far:
<select name="pickSort" id="chooseSort" onchange="changedOption">
<option value="lowHigh" id="lowHigh">Price Low-High</option>
<option value="highLow" id="lowHigh">Price High-Low</option>
</select>
<script>
function changedOption() {
var sel = document.getElementsByName('pickSort');
var sv = sel.value;
alert(sv);
}
</script>
A better way of doing this without the inline stuff:
document.getElementById("chooseSort").onchange = function() {
alert(this.value);
};
jsFiddle here.
You need to call the function with parentheses changedOption()
<select name="pickSort" id="chooseSort" onchange="changedOption()">

Select/Highlight option based on a div content

Below code suppose to match the dropdown list with the div content. If "Pineapple" is found, then select this option. I couldn't seem to find the error.
<head>
<script>
function displayResult(){
var myObject=document.getElementById("mySelect");
var myValue = $('#myContent').text();
for(var i=0; i<myObject.length; i++){
if(myObject.options[i].text == myValue){
myObject.options[i].selected = true;
(also tried - myObject.options[i].selectedIndex = i;)
break;
}
}
}
</script>
</head>
<body>
<div id="myContent">Pineapple</div>
<form>
Select your favorite fruit:
<select id="mySelect" size="4">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
</form>
<button type="button" onclick="displayResult()">Highlight Pineapple Option</button>
</body>
Note:
I want the option to be highlighted. Missing the closing bracket was a typo, corrected. Tried .selectedIndex=i, didn't seem to do the trick.
You are missing a } at the end of the function.
And you should either include jQuery library or change
var myValue = $('#myContent').text();
to
var myValue = document.getElementById('myContent').innerHTML;
A simpler trick to use, though, is (not a good trick afterall...see #RobG's comment)
function displayResult() {
var myObject = document.getElementById("mySelect");
var myValue = document.getElementById('myContent').innerHTML;
myObject.value = myValue;
}
but for IE the options will need to include the value attribute
<option value="Pineapple">Pineapple</option>
You're missing the closing bracket to displayResult.
Instead of:
> myObject.options[i].selected = true;
use
myObject.selectedIndex = i;
Setting the selected property to true doesn't necessarily make the option selected (it varies between browsers).
Oh, and you have a syntax error:
<script>
function displayResult(){
var myObject=document.getElementById("mySelect");
var myValue = $('#myContent').text();
for(var i=0; i<myObject.length; i++){
...
}
// missing closing } for function body
</script>

onchange function

I am trying to create a function to run when a select option is changed. In my select menu i have;
<form id="frame">
<select id="frame_color" onchange="fChange()">
<option value="0">Polished Black</option>
<option value="1">Grey</option>
</select>
</form>
The only thing that I want the fChange() function to do is update the variable that is holding the options value with the onchange value. So, the variable in the function fChange starts off by holding the value "0", and when I change it to "Grey" I want the variable to update to "1". I am having a hard time figuring out how to code the function properly. Any suggestions?
following get the selected option value ...
function fChange()
{
var val = $("#frame_color").val();
}
fChange = function(){
var value = document.getElementById("frame_color").value;
alert(value);
}
try this, which is jQuery
<script type="text/javascript">
$(document).ready(function () {
$('#frame_color').change(function(){
// your code should be here
});
});
</script>
on jQuery:
$(function(){
$('#frame_color').on('change',function(){
your_variable = $(this).val()
});
});
for non-jQuery, a quick way to do it is:
document.getElementById('frame_color').onchange = function(e){
your_variable = e.target.value;
}​
also, you might want to look at addEventListener for standards-compliant browsers, and attachEvent for IE6-8
var variable = 0;
function fChange()
{
var val = document.getElementById("frame_color").value;
variable = val;
}
<form id="frame">
<select id="frame_color" onchange="fChange()">
<option value="0">Polished Black</option>
<option value="1">Grey</option>
</select>
</form>

Why my jQuery does not return to me the value of <select>

My index.html:
<body>
<select id="car">
<option value="TOYOTA">TOYOTA</option>
<option value="BMW">BMW</option>
</select>
<input type=button id="get_btn" value="Get"></input>
<script src="myscript.js"></script>
</body>
myscript.js:
var btn=$('#get_btn');
btn.click(function(){
var car= $('#car').val;
alert(car);
});
When I press the get button, I expect an alert show the selected car, but I got an alert window with the jQuery val function code:
function (value) {
if (!arguments.length) {
var elem = this[0];
if (elem) {
....
Where goes wrong?
".val" is a function. Use:
var car= $('#car').val();
val is a function, not a variable. You need to amend your myscript.js code as follows:
var btn=$('#get_btn');
btn.click(function(){
var car = $('#car').val();
alert(car);
});
you have missing brackets :
var car= $('#car').val;
and should be :
var car= $('#car').val();

Categories