I have this code below. Trying to get the value of selected option but first one give error that test.parent is not a function and second variable get an empty string. How can I make this work?
<select unselectable="on" name="gender">
<option value="Male" unselectable="on">Male</option>
<option value="Female" unselectable="on">Female</option>
</select>
<input value="Submit" onclick="addItem(this)" type="button">
<script>
function addItem(test){
var selected_val1 = test.parent('#gender option:selected').val();
var selected_val2 = $("#gender option:selected").text();
}
</script>
You're passing this to the addItem() function, and caching it as test, and that's not a jQuery object, but a native DOM node.
Then you're doing test.parent('#gender option:selected').val();, but test had no parent method, nor does it have a parent select element.
The select is the previous element, so you should be using prev
$(test).prev('[name="gender"]').find('option:selected').val();
or just
$(test).prev('select').val();
seems easier
var selected_val1 = $(test).parent().find('select[name="gender"] option:selected').val();
Here's an example: http://jsfiddle.net/z96c7025/
Inline JS is not recommended, so I would go with something like:
$('#mybutton').on('click', addItem);
function addItem() {
//in this callback 'this' refers to the button that was clicked and,
//as #adeneo has rightly pointed out, it should be wrapped in $()
var selected_val1 = $(this).prev().val(),
selected_val2 = $(this).prev().find('option:selected').text();
alert( 'value: ' + selected_val1 + ' text: ' + selected_val2 );
}
$('#mybutton').on('click', addItem);
function addItem() {
var selected_val1 = $(this).prev().val(),
selected_val2 = $(this).prev().find('option:selected').text();
alert( 'value: ' + selected_val1 + ' text: ' + selected_val2 );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select unselectable="on" name="gender">
<option value="Male" unselectable="on">Male</option>
<option value="Female" unselectable="on">Female</option>
</select>
<input value="Submit" type="button" id="mybutton">
As others have said, inline JS is not always a good choice, but if you choose to do so, these modifications should help. The javascript can be much, much more simple.
HTML
<form>
<select name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<input value="Submit" onclick="addItem(this.form)" type="button"> </form>
</form>
JS
function addItem(form) {
console.log(form.gender.value)
}
JS Extended
function addItem(form) {
var gender = form.gender;
for ( var i=0; i<gender.length; i++) {
console.log('Option ' + i + ': ' + form.gender[i].value)
}
console.log('Selected option: ' + form.gender.value);
var unselectedIndex = ( form.gender.selectedIndex + (form.length - 1))
console.log('Unselected option: ' + form.gender[unselectedIndex].value)
}
Related
I am trying t create dynamic dropdown using a value of array but values are appending inline in option
<body onload="getdata()">
<select class="form-control" id="focusedinput" name="sBranchName" required>
<option name="sBranchName" id="branch_list" ></option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" ></script>
<script>
function getdata () {
var data =['rajkot','surat','delhi']
var mySelect = $('#branch_list');
for(let value of data){
console.log(value)
mySelect.append("<option>" + value + "</option>")
}
};
</script>
</body>
Can anyone suggest the proper way?
See this line:
mySelect.append("<option>" + value + "<option>")
You're missing a /.
You're also appending to the option rather than to the select. Try selecting the select instead:
$('#focusedinput').append("<option>" + value + "</option>")
function getdata() {
const data = ['rajkot', 'surat', 'delhi']
const mySelect = $('#focusedinput');
data.forEach((value) => {
mySelect.append("<option>" + value + "</option>");
});
}
getdata();
<select class="form-control" id="focusedinput" name="sBranchName" required>
<option name="sBranchName" id="branch_list" ></option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I am trying to wrap my head around the each function. In this fiddle here
I would like to iterate through the selected elements of the list box one by one.
Essentially I was expecting an output like this
found itemA
found itemB
However I get an output like this
found itemA,itemB
I would like to know why that is happening and how I can fix it.
This is the code I am using
HTML
<select multiple="multiple" size="5" id="test">
<option>itemA</option>
<option>itemB</option>
</select>
<br>
<button type="button" id="bid">test</button>
JQuery
$( "#bid" ).click(function() {
$("#test").each(function () {
console.log("found " + $(this).val());
});
});
You are iterating over the select and not the options. The function you passed to each is getting called just once. Change your selector to #test > option and, like the comments on the question, change val() to text().
$( "#bid" ).click(function() {
$("#test > option").each(function () {
console.log("found " + $(this).text());
});
});
You have to specify the elements selector. Using only #test won't iterate over options because you didn't actually refer to it.
$("#bid").click(function() {
$("#test option").each(function() {
console.log("found " + $(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple="multiple" size="5" id="test">
<option>itemA</option>
<option>itemB</option>
</select>
<br>
<button type="button" id="bid">test</button>
You'll want to use
$.each($("#test").prop("options"), function () {
console.log("found " + this.value);
});
or
$("#test").children().each(function () {
console.log("found " + this.value);
});
Here is an example that might explain it more: https://jsfiddle.net/Twisty/dr1tay6f/6/
HTML
<select multiple="multiple" size="5" id="test">
<option value="a">Item A</option>
<option value="b">Item B</option>
</select>
<br>
<button type="button" id="bid">test</button>
JavaScript
$(function() {
$("#bid").click(function() {
$("#test option").each(function(ind, el) {
console.log("At Index " + ind +" found Option with Value: " + $(el).val() + " and Label of: " + $(el).html());
});
});
});
The $(selector).each(callback(index, element)); will iterate over each element in the selector, passing it's index and element to the function.
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
i have little problem with ddslike jquery lib
I have two select box like this:
<select id="from">
<option value="1" data-imagesrc="img.png" data-description="USD">Dollar</option>
<option value="2" data-imagesrc="img.png" data-description="EUR">Euro</option>
</select>
<select id="to">
<option value="1" data-imagesrc="img.png" data-description="USD">Dollar</option>
<option value="2" data-imagesrc="img.png" data-description="EUR">Euro</option>
</select>
Javascript of SELECT BOX (Want just the design from ddslike):
<script type="text/javascript">
$(document).ready(function () {
$('#from_fees').ddslick({
width: 100,
});
$('#to_fees').ddslick({
width: 100,
});
});
</script>
Here my script that i wanted to fetch value of select's options:
$(function(){
$("#from").change(function(event){
//alert("Click event on Select has occurred!");
$("option:selected", $(this)).each(function(){
var obj = document.getElementById('from').value;
alert("selected value"+obj);
});
});
});
But i get no results !
I want get the two value from the two select in the same time.
Thank you.
First, you've got to be consistent with your IDs. You've got id="from" in the html, but you call .ddslick() on the element with id "from_fees".
If I understand, you'd like to get the values of each whenever either one changes. How about:
<script>
$('select').change(function(){
var to = $('#to').val();
var from = $('#from').val();
// alert("To: " + to + " and from: " + from + ".");
});
</script>
You don't need to use "this", because you want the value out of both of them.
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.