javascript with html select box - javascript

I have select box with default value,i want to retrieve default value and changed value using javascript,Below is my Html Select box:
<SELECT ID="TEST" NAME="TEST" ONCHANGE="TEST()">
<OPTION ID="1" VALUE="TEST1" SELECTED/>
<OPTION ID="2" VALUE="TEST2"/>
</SELECT>
Regards,
Raj

You can set custom attribute of the element in the onload event of the document:
window.onload = function() {
var oDDL = document.getElementById("TEST");
oDDL.setAttribute("default_value", oDDL.value);
};
Then to read it:
function Test() {
var oDDL = document.getElementById("TEST");
var strCurrentValue = oDDL.value;
var strDefaultValue = oDDL.getAttribute("default_value");
alert("Default value is: " + strDefaultValue + "\n Current value is: " + strCurrentValue);
}
Complete code and test case: http://jsfiddle.net/yahavbr/MbnH7/
Edit: to support more than one drop down, first pass reference in the onchange event like this:
<select id="TEST" name="TEST" onchange="Test(this);">
Then set the custom attribute in a loop:
window.onload = function() {
var arrDDLs = document.getElementsByTagName("select");
for (var i = 0; i < arrDDLs.length; i++) {
var oDDL = arrDDLs[i];
oDDL.setAttribute("default_value", oDDL.value);
}
};
And the test function also need minor change as it's not getting the drop down as argument:
function Test(oDDL) {
var strCurrentValue = oDDL.value;
var strDefaultValue = oDDL.getAttribute("default_value");
alert("Default value is: " + strDefaultValue + "\n Current value is: " + strCurrentValue);
}
Updated test case: http://jsfiddle.net/yahavbr/MbnH7/1/
Edit II: to show the previously selected value some name changes are required, plus storing the value every time it's changing. The onload becomes this:
window.onload = function() {
var arrDDLs = document.getElementsByTagName("select");
for (var i = 0; i < arrDDLs.length; i++) {
var oDDL = arrDDLs[i];
oDDL.setAttribute("previous_value", oDDL.value);
}
};
(Only change is the custom attribute name)
And the function becomes:
function Test(oDDL) {
var strCurrentValue = oDDL.value;
var strPreviousValue = oDDL.getAttribute("previous_value");
alert("Previous value is: " + strPreviousValue + "\n Current value is: " + strCurrentValue);
oDDL.setAttribute("previous_value", strCurrentValue);
}
(Name change plus setting the custom attribute)
Updated and hopefully final test case: http://jsfiddle.net/yahavbr/MbnH7/4/

why not have the onfocus event (vs. onload) store the current value. one solution might be to do something like this:
$(t).data("prev",$(t).val())
and then have the onchange use that:
var oldVal = $(t).data("prev");
thus when someone clicks on, or tabs into, the ui element it stores the current state, and then can use that if there is a resulting change. also it would need to change the value if the change was accepted so that if focus was not changed (ie: they stayed in the pulldown and changed the value again) and they changed their mind and chose another option that the state was preserved.
many of the examples that i have seen of this store state in a that seemed to be vulnerable to change/events elsewhere.

HTML:
<SELECT ID="TEST" NAME="TEST" ONCHANGE="TEST(this)">
<OPTION ID="1" VALUE="TEST1" SELECTED>TEST 1</OPTION>
<OPTION ID="2" VALUE="TEST2">TEST 2</OPTION>
</SELECT>
javascript:
// store currently selected value
var previousValue = document.getElementById('TEST').value;
function TEST(e) {
alert('old value = ' + previousValue);
alert('new value = ' + e.value);
// store new value
previousValue = e.value;
}
example here

EDIT - I answered wrong before - Here's a sample HTML page that does it.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>untitled</title>
<script type="text/javascript" language="javascript">
function showOptionValue(oSelect) {
var def;
for (var i=0; i<oSelect.options.length; ++i) //loop through select options
if (oSelect.options[i].defaultSelected){ //this option's defaultSelected property is set to true (from HTML: selected="selected")
def = oSelect[i].text; //or .value
}
var sel;
sel = oSelect[oSelect.selectedIndex].text;
alert (sel + ' : ' + def);
}
function resetSelect(oSelect) {
for (var i=0; i<oSelect.options.length; ++i) //loop through select options
if (oSelect.options[i].defaultSelected) //this option's defaultSelected property is set to true (from HTML: selected="selected")
oSelect.options[i].selected = true; //so, set its selected property to true, selecting it
showOptionValue(oSelect); //reset status
}
</script>
</head>
<body>
<form>
<!-- call handler function, pass Select object (represents drop-down list) -->
<SELECT NAME="cbo" onchange="showOptionValue(this)">
<OPTION VALUE="not_default">Not DEFAULT VALUE</OPTION>
<OPTION VALUE="1">Small</OPTION>
<!-- default value, preselected -->
<OPTION VALUE="2" selected="selected">Medium</OPTION>
<OPTION VALUE="3">Large</OPTION>
</SELECT>
<!-- call handler function, pass Select object using its name as a variable -->
<input type="button" value="Reset Drop-down" onclick="resetSelect(cbo)">
</form>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
<title>Hello world</title>
<script type="text/javascript">
function fn(){
var select = document.getElementById("selectbox");
alert(select.options[select.selectedIndex].value)
}
</script>
</head>
<body>
<header style="margin-left: 50%;">Welcome</header>
<select id="selectbox">
<option value="number 01">Number 01</option>
<option value="number 01">Number 02</option>
<option value="number 01">Number 03</option>
<option value="number 01">Number 04</option>
</select>
<button style="margin-top:10px; margin-left:15px;" onclick="fn()">Click me</button>
</body>
</html>

Related

Get selected item on select with js

Look, i'm getting crazy, i can't get the selected item inside a normal select dropdown list (The values of the list are created dynamiclly with js).
I have a list of items and that are the columns of a table and i want when i click on an item, the column is added to the table and if i click another time in that item the column is removed.
I've tried to use a change event with jquery and onchange event with js but if i select the item two times in a row the column is added but not removed because the value hasn't changed.
I've tried to give a onclick event to the options of the select but nothing happens when i click on one. I've tried to capturo the clicked option from the select with jquery with this code:
$("#selectTableLt").on("click", "option", function() {
let clickedOption = $(this);
console.log(clickedOption);
});
But nothing happens.
Can anyone help me with this, please? Thank you
Edit:
My html:
<select name="leftColumns" id="selectTableLt"></select>
I load the options with javascript but they look like:
<option value="opt1">Option 1</option>
It's very simple
Check this out
<!DOCTYPE html>
<html>
<head>
<title>Select from dropdown list</title>
</head>
<body>
<h1>Select from dropdown list</h1>
<p id="result">Result here</p>
<select id="country">
<option value="None">-- Select --</option>
<option value="ID1">America</option>
<option value="ID2" selected>India </option>
<option value="ID3">England</option>
</select>
<script>
function GetSelectedValue(){
var e = document.getElementById("country");
var result = e.options[e.selectedIndex].value;
document.getElementById("result").innerHTML = result;
}
function GetSelectedText(){
var e = document.getElementById("country");
var result = e.options[e.selectedIndex].text;
document.getElementById("result").innerHTML = result;
}
</script>
<br/>
<br/>
<button type="button" onclick="GetSelectedValue()">Get Selected Value</button>
<button type="button" onclick="GetSelectedText()">Get Selected Text</button>
</body>
</html>
here is a solution to handle the multiple click events and fetch the dropdown selected value
var oldValue = null;
$(document).on("click","#selectTableLt", function(){
s = $(this);
val = s.val();
if (oldValue == null) {
oldValue = val;
} else {
var newValue = s.val();
if (newValue != "") {
var finalVal = oldValue == s.val() ? oldValue : newValue;
console.log(finalVal)
}
$(document).unbind('click.valueCheck');
oldValue = null;
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectTableLt">
<option value="0">One</option>
<option value="1">Two</option>
</select>
You need to fetch the value using $.val() function
bind event to document in order to handle the dynamic event listener
$(document).on( eventName, selector, function(){} );
Using the Change Event:
$(document).on("change","#selectTableLt", function() {
let clickedOption = $(this).val();
console.log(clickedOption);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectTableLt">
<option value="0">One</option>
<option value="1">Two</option>
</select>
Using the Click Event:
$(document).on("click","#selectTableLt", function() {
let clickedOption = $(this).val();
console.log(clickedOption);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectTableLt">
<option value="0">One</option>
<option value="1">Two</option>
</select>

Javascript — Why does the getAttribute() function not work on certain attributes?

Why does the alert display the correct value (which is pl) when i use alert(el2.getAttribute("class"));but does not do so when I use alert(el2.getAttribute("value")); (which is supposed to be the value for each option such as sunny... etc).
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Allowance updater example</title>
</head>
<body>
<label for="weather">Select the weather type today: </label>
<select id="weather">
<option value="" class = "pl">--Make a choice--</option>
<option value="sunny" class = "pl">Sunny</option>
<option value="rainy" class = "pl">Rainy</option>
<option value="snowing" class = "pl">Snowing</option>
<option value="overcast" class = "pl">Overcast</option>
</select>
<p></p>
<script>
var el = document.querySelector("select");
var el2 = document.querySelector("option");
el.addEventListener("click", x);
function x() {
alert(el2.getAttribute("value"));
alert(el2.getAttribute("class"));
}
</script>
</body>
</html>
which is supposed to be the value for each option such as sunny... etc
No. It is supposed to be the value attribute for the particular element that is stored in e2.
var el2 = document.querySelector("option");
… and that is the first option element in the document.
<option value="" class = "pl">
… which is an empty string.
If you want to get all the options then you need to get them all (querySelectorAll) and then loop over the resulting list of elements as if it were an array.
You can't like this?
<script>
var el = document.querySelector("select");
el.addEventListener("change", x);
function x() {
alert(el.value);
}
</script>

Google HTML Service: write values from multiple selects in form to spreadsheet

I've been banging my head against this for the past several days and have finally broken down and admitted defeat. This is my first project utilizing Google HTML Service, and what I'm trying to do seems simple, but I can't get it to work. Here is what I want to happen...
User interacts with spreadsheet and needs to add additional rows with data
User selects an option from a custom menu item (got this working)
This selection launches an HTML service form (got this working)
User selects the values from two drop down lists and clicks submit
The selected options read read (working kind of...) and passed to the .js (this is where I'm stuck), which will create the rows and place the data.
Below is my code:
Function that launches the HTML Service
function AddAdditionalApplicant() {
var ss = SpreadsheetApp.getActiveSpreadsheet(),
html = HtmlService.createHtmlOutputFromFile('index');
ss.show(html);
}
index.html
<form name="AddApplicant" onsubmit="formSubmit()">
<p><b>What Type?</b></p>
<select name="NumOfApp" id="NumOfApp">
<option value="1">1</option>
<option value="2">2</option>
<option value="Cosigner">Cosigner</option>
</select>
<p><b>How Many?</b></p>
<select name="TypeOfApp" id="TypeOfApp">
<option value="Roommate">Roommate</option>
<option value="Cosigner">Cosigner</option>
</select>
<p></p>
<div>
<!--<input type="submit" class="button redButton" value="Submit" onclick="formSubmit()">-->
<input type="submit" class="button redButton" value="Submit">
</div>
</form>
<script type="text/javascript">
function formSubmit() {
//var a=document.getElementById('NumOfApp').selectedIndex;
//var b=document.getElementById('NumOfApp').options;
//alert("Index: " + b[a].index + " is " + b[a].text);
//var x=document.getElementById('TypeOfApp').selectedIndex;
//var y=document.getElementById('TypeOfApp').options;
//alert("Index: " + y[x].index + " is " + y[x].text);
google.script.run.getValuesFromForm(document.forms[0]);
}
</script>
If you uncomment the lines that are commented out you will see that the values are read correctly. Now, here is where it fails... I attempt to pass the form as an object to the function "getValuesFromFrom" using
google.script.run.getValuesFromForm(document.forms[0]);
Function getValuesFromFrom
function getValuesFromForm(AppForm){
Browser.msgbox("success") /attempt to test and see if the execution gets this far...no go
//var a=AppForm['NumOfApp'].selectedIndex;
//var b=AppForm['NumOfApp'].options;
//Logger.log(b[a])
//
//var x=AppForm.TypeOfApp.selectedIndex;
var type = AppForm.TypeOfApp.options[AppForm.TypeOfApp.selectedIndex].value;
Logger.log(type)
}
Nothing happens... the browser msgBox does not pop up. What am I missing? Also, how can I get the form to close automatically when the "Submit" button is pressed. Any help is greatly appreciated.
EDIT:
After going back and forth with #Sandy Good I realized the "AppForm" variable in the getValuesFromForm function was undefined, which means that the form object was not being passed to the function from the html. I tried another approach, and just attempted to pass a string variable to the function by altering the script portion of the html code like this
var x=document.getElementById('TypeOfApp').selectedIndex;
var y=document.getElementById('TypeOfApp').options;
//alert("Index: " + y[x].index + " is " + y[x].text);
var type=y[x].value
// google.script.run.getValuesFromForm(y[x], b[a]);
google.script.run.withFailureHandler(google.script.host.close)
.getValuesFromForm(type);
This was successful, while this...
var x=document.getElementById('TypeOfApp').selectedIndex;
var y=document.getElementById('TypeOfApp').options;
//alert("Index: " + y[x].index + " is " + y[x].text);
var type=y[x]
// google.script.run.getValuesFromForm(y[x], b[a]);
google.script.run.withFailureHandler(google.script.host.close)
.getValuesFromForm(type);
was not!
So the question remains, what was I doing wrong previously?
EDIT: July 10th...Working code
Function that launches the HTML Service
function AddAdditionalApplicant() {
var ss = SpreadsheetApp.getActiveSpreadsheet(),
html = HtmlService.createHtmlOutputFromFile('index');
ss.show(html);
}
index.html
<form name="AddApplicant" onsubmit="formSubmit(this)">
<p><b>How Many?</b></p>
<select name="NumOfApp" id="NumOfApp">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<p><b>What Type?</b></p>
<select name="TypeOfApp" id="TypeOfApp">
<option value="Roommate">Roommate</option>
<option value="Cosigner">Cosigner</option>
</select>
<p></p>
<div>
<!--<input type="submit" class="button redButton" value="Submit" onclick="formSubmit()">-->
<input type="submit" class="button redButton" value="Submit">
</div>
</form>
<script type="text/javascript">
function formSubmit(argTheFormElement) {
google.script.run
.withFailureHandler(myFailureFunction)
.withSuccessHandler(google.script.host.close)
.getValuesFromForm(argTheFormElement);
}
function myFailureFunction(argError) {
alert("There was an error: " + argError.message);
google.script.host.close();
}
</script>
Function that receives the Form element
function getValuesFromForm(AppFormElement){
var ss = SpreadsheetApp.getActive();
var s = ss.getActiveSheet();
var sname = s.getName();
var num = AppFormElement.NumOfApp
var type = AppFormElement.TypeOfApp
var activeRow = s.getActiveCell().getRow();
var addCell = s.getRange(activeRow,2);
if (type == "Roommate") {
for(var i = 0; i < num; ++i){
AddRoommate(activeRow,addCell,sname,s);
}
}else if (type == "Cosigner"){
for(var i = 0; i < num; ++i){
AddCosigner(activeRow,addCell,sname,s);
}
}
s.setActiveRange(addCell.offset(1,1));
}
Hope this helps someone out!!!
Change your form tag, and add this to the function:
onsubmit="formSubmit(this)"
Then modify your function:
function formSubmit(argTheFormElement) {
Then put the variable argTheFormElement into the google.script.run.function(parameter);
google.script.run.getValuesFromForm(argTheFormElement);
That will pass all input values to the server. The get the values out, you must use the name of the name tag.
var type = AppForm.NumOfApp; //Get NumOfApp value
To make the dialog close, use:
google.script.host.close;
google.script.host.close

How to get selected value from Dropdown list in JavaScript

How can you get the selected value from drop down list using JavaScript? I have tried the following but it does not work.
var sel = document.getElementById('select1');
var sv = sel.options[sel.selectedIndex].value;
alert(sv);
It is working fine with me.
I have the following HTML:
<div>
<select id="select1">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
<br/>
<button onClick="GetSelectedItem('select1');">Get Selected Item</button>
</div>
And the following JavaScript:
function GetSelectedItem(el)
{
var e = document.getElementById(el);
var strSel = "The Value is: " + e.options[e.selectedIndex].value + " and text is: " + e.options[e.selectedIndex].text;
alert(strSel);
}
See that you are using the right id. In case you are using it with ASP.NET, the id changes when rendered.
Direct value should work just fine:
var sv = sel.value;
alert(sv);
The only reason your code might fail is when there is no item selected, then the selectedIndex returns -1 and the code breaks.
Hope it's working for you
function GetSelectedItem()
{
var index = document.getElementById(select1).selectedIndex;
alert("value =" + document.getElementById(select1).value); // show selected value
alert("text =" + document.getElementById(select1).options[index].text); // show selected text
}
Here is a simple example to get the selected value of dropdown in javascript
First we design the UI for dropdown
<div class="col-xs-12">
<select class="form-control" id="language">
<option>---SELECT---</option>
<option>JAVA</option>
<option>C</option>
<option>C++</option>
<option>PERL</option>
</select>
Next we need to write script to get the selected item
<script type="text/javascript">
$(document).ready(function () {
$('#language').change(function () {
var doc = document.getElementById("language");
alert("You selected " + doc.options[doc.selectedIndex].value);
});
});
Now When change the dropdown the selected item will be alert.
I would say change var sv = sel.options[sel.selectedIndex].value;
to var sv = sel.options[sel.selectedIndex].text;
It worked for me. Directing you to where I found my solution
Getting the selected value dropdown jstl
According to Html5 specs you should use --
element.options[e.selectedIndex].text
e.g. if you have select box like below :
<select id="selectbox1">
<option value="1">First</option>
<option value="2" selected="selected">Second</option>
<option value="3">Third</option>
</select>
<br/>
<button onClick="GetItemValue('selectbox1');">Get Item</button>
you can get value using following script :
<script>
function GetItemValue(q) {
var e = document.getElementById(q);
var selValue = e.options[e.selectedIndex].text ;
alert("Selected Value: "+selValue);
}
</script>
Tried and tested.

Dynamic javascript select dropdown

This was interesting. In a select dropdown, trying not to use jQuery (with the exception of easing some of my pain on recreation), I ran into an issue that doesn't properly let any current browsers catch the proper selected option. Here is my code, for the page that recreates the issue (remember, no jQuery to necessarily solve issue, but more or less just telling me what I am doing wrong.
This one has me stumped.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<div id="select-holder" />
<input id="some-button" type="button">
<script type="text/javascript">
$("#some-button").click(function(){
var select_element = document.createElement('select');
select_element.setAttribute("id", "some-id");
select_element.setAttribute("name", "some-name");
var options = new Array();
for ( var i = 0; i < 3; i++ ){
options.push(new Option("Option " + i, "Value" + i, false, false));
}
options[1].setAttribute("selected", "selected");
for ( var option in options ){
select_element.appendChild(options[option]);
}
$("#select-holder").append(select_element);
});
</script>
</body>
</html>
The html this creates is:
<select id="some-id" name="some-name">
<option value="Value0">Option 0</option>
<option value="Value1" selected="selected">Option 1</option>
<option value="Value2">Option 2</option>
</select>
But the anomaly here is that (in firefox at least), the selected option ends up being Option 0, which isn't the selected DOM element. In IE6, this select dropdown doesn't work at all.
There is an alternate method that does work, which includes piecing the options together manually, which works in all browsers that I have tested.
A small change made it work for me in Firefox:
...
//options[1].setAttribute("selected", "selected");
options[1].selected = true;
...
I'm manipulating the DOM element's attributes directly. Not sure why your method doesn't work. Maybe you should keep both lines so that the HTML generated has the selected = "selected" in it.
some old thread - however try something like this:
var idx=0;
while(obj.options[idx]) {
if(obj.options[idx].value==value) obj.options[idx].setAttribute('selected',true);
else obj.options[idx].removeAttribute('selected');
idx++;
}
Use selectedIndex to set the selected index of a select object.
options.selectedIndex = 1;
Here is the working code, which seems like more of a Hack!
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<div id="select-holder" />
<input id="some-button" type="button">
<script type="text/javascript">
$("#some-button").click(function(){
var select_element = document.createElement('select');
select_element.setAttribute("id", "some-id");
select_element.setAttribute("name", "some-name");
for ( var i = 0; i < 3; i++ ){
var option_element = document.createElement('option');
option_element.setAttribute('value', "Value" + i);
option_element.appendChild( document.createTextNode( "Option " + i ) );
if (i == 1){
option_element.setAttribute("selected", "selected");
}
select_element.appendChild(option_element);
}
$("#select-holder").append(select_element);
});
</script>
</body>
</html>
options[1].setAttribute("selected", "selected");
is likely where your issue lies. The output you're getting is:
<option value="Value1" selected="selected">Option 1</option>
and the standard is:
<option value="Value1" selected>Option 1</option>
You may be able to do:
options[1].selected = true;

Categories

Resources