Javascript error document.myform.mydiv is undefined - javascript

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>

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)

Javascript change a select list based on passed variables

I want to pass a variable from another page and have it effect the first select in a form on my current page. For example if my url is:
currentPage.html?classType=BATR1
I want the select to display the corresponding option.
This is what I am currently trying:
<script>
function setClassType(param) {
var val = document.URL;
var url = val.substr(val.indexOf(param))
var n = url.replace(param+"=","");
document.getElementById(n).selected = true;
}
setClassType("classType");
</script>
<form>
<select>
<option id="test">Test</option>
<option id="BATR1">Backflow Assembly Tester Recertification 1-Day</option>
<option id="CCSC">Cross-Connection Specialist Update</option>
</select>
</form>
I have also tried this:
<script>
function setClassType(param) {
var val = document.URL;
var url = val.substr(val.indexOf(param))
var n = url.replace(param+"=","");
document.getElementById("courseType").value = n;
}
setClassType("classType");
</script>
<form>
<select id="courseType">
<option value="test">Test</option>
<option value="BATR1">Backflow Assembly Tester Recertification 1-Day</option>
<option value="CCSC">Cross-Connection Specialist Update</option>
</select>
</form>
I'm pretty much a beginner at scripting and I just can't seem to get it to work. Any help would be much appreciated!

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

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 roller on radio button's onclick

I have four radio buttons to select a country. When a user clicks on any of the radio button, I use Ajax to get the states of that country. In order to show the end user that we are processing the data, I use a roller image(gif).
When any user clicks on of country radio, in the method (onclick event of radio), loadStates(), I enable the roller image by setting it's display property to 'inline'.
Then send a request to the server using Ajax(for showing a working example, I have removed that code and have inserted a "sleep" instead, just to show that it takes some time).
Right after getting the result, I put back the display property to 'none'.
However it is not working. Can anybody tell me how to fix it ?
PS : I dont want to use jQuery for the time being, only Javascript please.
<html>
<head>
<script type="text/javascript">
window.onload = init;
function init() {
countryFunctions();
}//init
function countryFunctions() {
var inputElems = document.forms[0].getElementsByTagName('input');
for (var i = 0, j = inputElems.length; i < j; i++) {
var elemName = inputElems[i].name;
if ( typeof elemName != 'undefined' && elemName === 'country' ) {
//inputElems[i].onmouseup = showRoller;
inputElems[i].onclick = loadStates;
}//if
}//for
return;
}
function loadStates() {
var action = 'get_states';
document.getElementById("fSpinner").style.display = "inline";
//alert("hi........");
var result = doLoad(action);
document.getElementById("countryStates").innerHTML = result;
document.getElementById("fSpinner").style.display = "none";
}
function doLoad(action) {//A dummy function just show what it returns (actually it is Ajax)
sleep(7000);
var value = "\
<p>\
Which state of the country would you like to go?\
</p>\
<select name=\"state\">\
<option value=\"1362\">Delhi</option>\
<option value=\"481\">Kerala</option>\
<option value=\"666\">Punjab</option>\
<option value=\"668\">Kashmir</option>\
</select>";
return(value);
}
function sleep(ms) {
var unixtime_ms = new Date().getTime();
while(new Date().getTime() < unixtime_ms + ms) {}
}
</script>
<style type="text/css">
#fSpinner { display:none; }
</style>
</head>
<body>
<form>
<p>What country do you belong to?</p>
<p>
<input name="country" value="in" type="radio"> India
<input name="country" value="au" type="radio"> Australia
<input name="country" value="nz" type="radio"> New Zealand
<input name="country" value="my" type="radio"> Malaysia
<span id="fSpinner">
<img style="vertical-align:text-bottom;" src="http://107.20.148.146/shak/images/roller.gif">
</span>
</p>
<div id="countryStates"></div>
</form>
</body>
</html>
The sleep function "blocks" the browser, the page is not refreshed until the function returns.
To simulate an asynchronous process, like an AJAX call, use setTimeout instead:
function loadStates() {
var action = 'get_states';
document.getElementById("fSpinner").style.display = "inline";
setTimeout( function() {
var value = "\
<p>\
Which state of the country would you like to go?\
</p>\
<select name=\"state\">\
<option value=\"1362\">Delhi</option>\
<option value=\"481\">Kerala</option>\
<option value=\"666\">Punjab</option>\
<option value=\"668\">Kashmir</option>\
</select>";
document.getElementById("countryStates").innerHTML = value;
document.getElementById("fSpinner").style.display = "none";
}, 7000) ;
}

Categories