Getting an option value to call a javascript function - javascript

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,'','');
}

Related

Google Sheets Script Editor HTML User Interface not able to read return type

I am attempting to take a custom array from the script editor and return it to my HTML UI in order to create a customized drop down menu search bar.
The first major problem I am encountering is that I am unable to assign a variable to a value from a function's return type. Below is the code I have written:
CODE:
function showSidebar() {
var html = HtmlService.createHtmlOutputFromFile('Search5')
.setTitle('My custom sidebar')
.setWidth(300);
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.showSidebar(html);
}
function called(value){
Logger.log("CALLED");
Logger.log(value);
var html= HtmlService.createHtmlOutputFromFile('Search5').setTitle("NEW sidebar");
SpreadsheetApp.getUi().showSidebar(html);
}
function getArray(){
Logger.log("get array called");
var array = ["test","a", "b", "c"];
return array;
}
function counter(i){
Logger.log(i);
}
HTML:
<!DOCTYPE html>
<html>
<head>
<title>HTML form Tag</title>
</head>
<body>
<form action="" method = "get">
<select name="cars" id = "test">
<div id="wrapper"></div>
<option value="volvo">Volvo XC90</option>
<option value="saab">Saab 95</option>
<option value="mercedes">Mercedes SLK</option>
<option value="audi">Audi TT</option>
<option value="select">SELECTED</option>
<option value="audi">Audi TT</option>
</select>
<input type="submit" name = "submitButton" onclick = "get()" value="Submit">
</form>
<script>
var array[];
function get(){
var e = document.getElementById("test");
var strUser = e.options[e.selectedIndex].value;
google.script.run.called(strUser);
}
function read(){
array = google.script.run.getArray();
google.script.run.counter(9); //debugging purposes
}
function test(){
google.script.run.counter();
}
function addHtml(){
read();
google.script.run.counter(array[3]); //debugging purpoes
var text = "";
for (i = 0; i < array.length; i++) {
text += '<option value="' + i+ '">'+ i+ '</option>\n';
google.script.run.counter(text); //debugging purposes
}
document.getElementById("wrapper").innerHTML = text;
}
window.onload = function () {
addHtml();
}
</script>
</body>
</html>
The line of code
document.getElementById("wrapper").innerHTML = text;
is intended to customize the drop down menu options. However, that doesn't seem to be working as well despite extensive research.
Back to the original question, why is my HTML code unable to assign the return type from my script to the javascript variable within my HTML file?
Thanks.
You want to use the values from getArray() of Google Apps Script at Javascript.
If my understanding is correct, how about this modification?
Modification points:
Modify from var array[]; to var array = [];.
Move <div id="wrapper"></div> to outside of select.
In your current script, I think that an error occurs.
google.script.run doesn't return values. When you want to use the returned values from Google Apps Script side, please use withSuccessHandler().
google.script.run works with the asynchronous process.
In your script, when addHtml() is run, google.script.run.counter(array[3]) and the for loop is run before read() is finished. By this, the undefined array is used.
When above points are reflected to your script, it becomes as follows.
Modified script:
In this modification, your Javascript was modified.
<!DOCTYPE html>
<html>
<head>
<title>HTML form Tag</title>
</head>
<body>
<form action="" method = "get">
<div id="wrapper"></div> <!-- Modified -->
<select name="cars" id = "test">
<option value="volvo">Volvo XC90</option>
<option value="saab">Saab 95</option>
<option value="mercedes">Mercedes SLK</option>
<option value="audi">Audi TT</option>
<option value="select">SELECTED</option>
<option value="audi">Audi TT</option>
</select>
<input type="submit" name = "submitButton" onclick = "get()" value="Submit">
</form>
<script>
var array = []; // Modified
function get(){
var e = document.getElementById("test");
var strUser = e.options[e.selectedIndex].value;
google.script.run.called(strUser);
}
function test(){
google.script.run.counter();
}
function read() { // Modified
google.script.run.withSuccessHandler(addHtml).getArray();
}
function addHtml(e){ // Modified
array = e;
var text = "";
for (i = 0; i < array.length; i++) {
text += '<option value="' + i+ '">'+ i+ '</option>\n';
}
document.getElementById("wrapper").innerHTML = text;
}
window.onload = function() {
read(); // Modified
}
</script>
</body>
</html>
References:
Class google.script.run
withSuccessHandler(function)

How to call variables out function in javascript

I created this code in javascript, this code work fine, the code use drop-down to select item.
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
</head>
<body><br><div id="id6"></div>
Select an item from the following list:<br />
<select id="select" onchange="myFuntam()">
<option value="">choose
<option value="var_1">car1
<option value="var_2">car2
<option value="var_3">car3
<option value="var_4">car4
</select>
<script>
function myFuntam() {
var x = document.getElementById("select").value;
url="http//domain1.com";
ur2="http//domain2.com";
ur3="http//domain3.com";
ur4="http//domain4.com";
var link_1;
if (x == "var_1") {
link_1=url;
}
if (x == "var_2") {
link_1=ur2;
}
if (x == "var_3") {
link_1=ur3;
}
if (x == "var_4") {
link_1=ur4;
}
document.getElementById("id6").innerHTML = "You selected: " + link_1;
}
</script>
</body>
</html>
Now i need to call variable link_1 out of function, allow me to use this variable with another function or any where out the function.
i try to use this code
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
</head>
<body><br><div id="id6"></div>
Select an item from the following list:<br />
<select id="select" onchange="myFuntam()">
<option value="">choose
<option value="var_1">car1
<option value="var_2">car2
<option value="var_3">car3
<option value="var_4">car4
</select>
<script>
function myFuntam() {
var x = document.getElementById("select").value;
url="http//domain1.com";
ur2="http//domain2.com";
ur3="http//domain3.com";
ur4="http//domain4.com";
var link_1;
if (x == "var_1") {
link_1=url;
}
if (x == "var_2") {
link_1=ur2;
}
if (x == "var_3") {
link_1=ur3;
}
if (x == "var_4") {
link_1=ur4;
}
return link_1;
}
document.getElementById("id6").innerHTML = "You selected: " + link_1;
</script>
</body>
</html>
but this code not correct, link_1 is undefined, so how i use link_1 out of function.
The basics to get it done :
var link_1 = 'foobar';
function ....() { something with link_1; }
console.log(link_1);
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="id6"></div>
Select an item from the following list:<br />
<select id="select" onchange="myFuntam()">
<option value="">choose
<option value="var_1">car1
<option value="var_2">car2
<option value="var_3">car3
<option value="var_4">car4
</select>
<script>
function myFuntam() {
var x = document.getElementById("select").value;
url="http//domain1.com";
ur2="http//domain2.com";
ur3="http//domain3.com";
ur4="http//domain4.com";
var link_1;
if (x == "var_1") {
link_1=url;
}
if (x == "var_2") {
link_1=ur2;
}
if (x == "var_3") {
link_1=ur3;
}
if (x == "var_4") {
link_1=ur4;
}
return link_1;
}
function secondfunction(){
var linkvalue=myFuntam();
alert(linkvalue);
}
document.getElementById("id6").innerHTML = "You selected: " + myFuntam();
</script>
</body>
</html>
An alternative to using a variable, is to store the information in the DOM. You will save some code logic by storing those URL strings in each of the option nodes, as HTML5 data attributes.
The selected URL is then quite easily available.
var sel = document.getElementById('select');
function myFuntam() {
console.log(sel.options[sel.selectedIndex].dataset.url);
return sel.options[sel.selectedIndex].dataset.url;
}
Select an item from the following list:<br>
<select id="select" onchange="myFuntam()">
<option value="">choose
<option value="var_1" data-url="http//domain1.com">car1</option>
<option value="var_2" data-url="http//domain2.com">car2</option>
<option value="var_3" data-url="http//domain3.com">car3</option>
<option value="var_4" data-url="http//domain4.com">car4</option>
</select>
You can of course still decide to store that URL in a global variable, but as you can see, you don't need a lot of logic any more to retrieve it dynamically. Calling the function will just give you the URL you need without much hassle.
You have to declare the var outside the function so the function changes its declared value and you can keep using it the way you wanted after your function is done.
var link_1;
function myFunction() {
link_1 = 'www.anysite.com';
}
myFunction();
//now the var can be used outside
console.log(link_1);
//Anothe option could be
var link;
function myFunction2() {
link = 'www.otherwebsite.com';
return link;
}
link_2 = myFunction2();
console.log(link_2);
The third option could be using localStorage if the other ones did not work.
localStorage.setItem('link_1', link_1_value);
var aLink = localStorage.getItem('link_1');
Choose the one that suits your needs.

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;
};

Javascript multiple select

For a project I am working on, I need a multiple input list with a one click (de)selection, which work with the Internet Explorer (10). I found and modified this code, which is working very well:
But there is a problem:
The value of the selected options should be sent through the Post-Method to a PHP-script, but it sends only one selected value. After searching the web, I found out that I needed to name the NAME of my <select> like an array. So I changed NAME="sel_current" to NAME="sel_current[]". But with this change, this script stopped to work.
I hoped a change in document.forms[0].sel_current in init() to document.forms[0].sel_current[] would fix it, but it doesn't.
<HTML>
<HEAD>
<TITLE>Multi-select test</TITLE>
<SCRIPT LANGUAGE="JavaScript">
var multiSelect_current = new Object();
function storemultiSelect_current_current(obj) {
var name = obj.name;
multiSelect_current[name] = new Array();
for (var i=0; i<obj.options.length; i++) {
multiSelect_current[name][i] = obj.options[i].selected;
}
}
function changemultiSelect_current(obj) {
var name = obj.name;
for (var i=0; i<obj.options.length; i++) {
if (obj.options[i].selected) {
multiSelect_current[name][i] = !multiSelect_current[name][i];
}
obj.options[i].selected = multiSelect_current[name][i];
}
}
function init() {
storemultiSelect_current_current(document.forms[0].sel_current);
}
</SCRIPT>
</HEAD>
<BODY onLoad="init()">
<FORM>
<SELECT NAME="sel_current" MULTIPLE METHOD="post" SIZE=10 onChange="changemultiSelect_current(this)">
<OPTION value="1">1111</OPTION>
<OPTION value="2" selected>2222</OPTION>
<OPTION value="3">3333</OPTION>
<OPTION value="4">4444</OPTION>
<OPTION value="5" selected>5555</OPTION>
<OPTION value="6">6666</OPTION>
<OPTION value="7">7777</OPTION>
</SELECT>
</FORM>
</BODY>
</HTML>
You can use JSON.stringify(multiSelect_current[name]) finally, when sending to your server.
In the function storemultiSelect_current_current's for loop, modify this : multiSelect_current[name][i][obj.options[i].innerText] = (obj.options[i].selected == true);
screenshot :

Javascript error document.myform.mydiv is undefined

I have some javascript which is taking an input from a URL such as...
www.mydomain.com/?dropdown=Alpha
This will then pre-select Alpha from the dropdown box located at myform -> mydiv
function show(choice) {
var success = -1;
for (var i=0; i < document.myform.mydiv.length; i++) {
if (document.myform.mydiv.options[i].text == choice)
success = [i];
}
document.myform.mydiv.selectedIndex=success;
}
var choice = (location.href.split("?")[1] || '').split("=")[1];
Everything works fine apart from if you visit the url with no extension so www.mydomain.com - It then throws the following error...
document.myform.mydiv is undefined
The drop down html is...
<form name="myform">
<select name="mydiv">
<option value="1">Alpha</option>
<option value="2">Beta</option>
<option value="3">Gamma</option>
<option value="4">Delta</option>
</select>
</form>
<script>
show(choice);
</script>
This is pretty self explanatory and I understand that this is because it is undefined, my question is how do I add a check to fix?
I think your java script Function called before the Form Tag elements implementation... So only this error occurs...
Try to call that function from any one of the form element Events... Then it will work...
Just like below...
<html>
<head>
<script>
var urlpath = "www.mydomain.com/?dropdown=Alpha"
var choice = (urlpath.split("?")[1] || '').split("=")[1];
function show()
{
var success = -1;
for (var i=0; i < document.myform.mydiv.length; i++) {
if (document.myform.mydiv.options[i].text== choice)
success = i;
}
document.myform.mydiv.selectedIndex=success;
}
</script>
</head>
<body>
<form name="myform">
<select name="mydiv" onchange="show();">
<option value="2">Beta</option>
<option value="3">Gamma</option>
<option value="4">Delta</option>
<option value="1">Alpha</option>
</select>
</form>
</body>
</html>

Categories