Javascript multiple select - javascript

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 :

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)

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

How to set selectedIndex of select element using display text?

How to set selectedIndex of select element using display text as reference?
Example:
<input id="AnimalToFind" type="text" />
<select id="Animals">
<option value="0">Chicken</option>
<option value="1">Crocodile</option>
<option value="2">Monkey</option>
</select>
<input type="button" onclick="SelectAnimal()" />
<script type="text/javascript">
function SelectAnimal()
{
//Set selected option of Animals based on AnimalToFind value...
}
</script>
Is there any other way to do this without a loop? You know, I'm thinking of a built-in JavaScript code or something. Also, I don't use jQuery...
Try this:
function SelectAnimal() {
var sel = document.getElementById('Animals');
var val = document.getElementById('AnimalToFind').value;
for(var i = 0, j = sel.options.length; i < j; ++i) {
if(sel.options[i].innerHTML === val) {
sel.selectedIndex = i;
break;
}
}
}
<script type="text/javascript">
function SelectAnimal(){
//Set selected option of Animals based on AnimalToFind value...
var animalTofind = document.getElementById('AnimalToFind');
var selection = document.getElementById('Animals');
// select element
for(var i=0;i<selection.options.length;i++){
if (selection.options[i].innerHTML == animalTofind.value) {
selection.selectedIndex = i;
break;
}
}
}
</script>
setting the selectedIndex property of the select tag will choose the correct item. it is a good idea of instead of comparing the two values (options innerHTML && animal value) you can use the indexOf() method or regular expression to select the correct option despite casing or presense of spaces
selection.options[i].innerHTML.indexOf(animalTofind.value) != -1;
or using .match(/regular expression/)
If you want this without loops or jquery you could use the following
This is straight up JavaScript. This works for current web browsers. Given the age of the question I am not sure if this would have worked back in 2011. Please note that using css style selectors is extremely powerful and can help shorten a lot of code.
// Please note that querySelectorAll will return a match for
// for the term...if there is more than one then you will
// have to loop through the returned object
var selectAnimal = function() {
var animals = document.getElementById('animal');
if (animals) {
var x = animals.querySelectorAll('option[value="frog"]');
if (x.length === 1) {
console.log(x[0].index);
animals.selectedIndex = x[0].index;
}
}
}
<html>
<head>
<title>Test without loop or jquery</title>
</head>
<body>
<label>Animal to select
<select id='animal'>
<option value='nothing'></option>
<option value='dog'>dog</option>
<option value='cat'>cat</option>
<option value='mouse'>mouse</option>
<option value='rat'>rat</option>
<option value='frog'>frog</option>
<option value='horse'>horse</option>
</select>
</label>
<button onclick="selectAnimal()">Click to select animal</button>
</body>
</html>
document.getElementById('Animal').querySelectorAll('option[value="searchterm"]');
in the index object you can now do the following:
x[0].index
Try this:
function SelectAnimal()
{
var animals = document.getElementById('Animals');
var animalsToFind = document.getElementById('AnimalToFind');
// get the options length
var len = animals.options.length;
for(i = 0; i < len; i++)
{
// check the current option's text if it's the same with the input box
if (animals.options[i].innerHTML == animalsToFind.value)
{
animals.selectedIndex = i;
break;
}
}
}
You can set the index by this code :
sel.selectedIndex = 0;
but remember a caution in this practice, You would not be able to call the server side onclick method if you select the previous value selected in the drop down..
Add name attribute to your option:
<option value="0" name="Chicken">Chicken</option>
With that you can use the HTMLOptionsCollection.namedItem("Chicken").value to set the value of your select element.
You can use the HTMLOptionsCollection.namedItem()
That means that you have to define your select options to have a name attribute and have the value of the displayed text.
e.g
California

How to get the value of a multiple option dropdown?

Say I have this dropdown:
<select name="color" multiple="multiple">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
So basically more than 1 color can be selected. What I'd like is that if a user selects red, and then clicks green, i'd like a function to be called each time which pops up a message box saying the color which was most recently clicked.
I've tried this:
<option value="red" onclick="alert('red');">Red</option>
<option value="green" onclick="alert('green');">Green</option>
<option value="blue" onclick="alert('blue');">Blue</option>
This works in firefox and chrome, but not in IE.
Any ideas?
$("select[name='color']").change(function() {
// multipleValues will be an array
var multipleValues = $(this).val() || [];
// Alert the list of values
alert(multipleValues[multipleValues.length - 1]);
});
Here's another examples: http://api.jquery.com/val/
The following code should do what I think you're after. Each time an item is selected, it compares the current list of selections against the previous list, and works out which items have changed:
<html>
<head>
<script type="text/javascript">
function getselected(selectobject) {
var results = {};
for (var i=0; i<selectobject.options.length; i++) {
var option = selectobject.options[i];
var value = option.value;
results[value] = option.selected;
}
return results;
}
var currentselect = {};
function change () {
var selectobject = document.getElementById("colorchooser");
var newselect = getselected(selectobject);
for (var k in newselect) {
if (currentselect[k] != newselect[k]) {
if (newselect[k]) {
alert("Option " + k + " selected");
} else {
alert("Option " + k + " deselected");
}
}
}
currentselect = newselect;
}
</script>
</head>
<body>
<select id="colorchooser"
name="color"
multiple="multiple"
onchange='javascript:change();'
>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
</body>
</html>
It should work just as well in Internet Explorer as Firefox et al.
Since you using jQuery,I suggest you to take a look at this superb plugins. This plugins will transform a multiple select dropdown into a checkbox list, so user can select multiple values with easy.
To get the values, I suggest you use fieldValue methods from jQuery form plugins. It's a robust way to get value from any type of form element. Beside, you can use this plugins to submit your form via AJAX easily.
This will alert only the last (most recent) selected value. Calling $(this).val() using the select's change handler will return an array of all your selected values:
$(document).ready(function() {
$("select[name=color] option").click(function() {
alert($(this).val());
});
});
I am not sure what you exactly want. This will always alert the last selected color:
$(function(){
var selected = Array();
$('select[name=color] option').click(function() {
if($(this).is(':selected')) {
selected.push($(this).val());
}
else {
for(var i = 0; i < selected.length;i++) {
if(selected[i] == $(this).val()) {
selected = selected.splice(i,1);
}
}
}
alert(selected[selected.length -1])
});
});
The array is used to maintain the history of selected colors.
For the last clicked color, it is simpler:
$(function(){
$('select[name=color] option').click(function() {
alert($(this).val());
});
});
This is so complicated to accomplish that I used a simpler option of listing the items with a checkbox next to them and a select/unselect all button. That works much better and is also supported by IE. Thanks to everyone for their answers.

Categories