I'm working on an interface on Google Sheet with JS & Google App Script.
The purpose is to click on a button, fill a html form (with an inputbox, a dropdown and a dropdown with multiple choices) which appears at the side, add the data in the sheet and write it in an alert box.
I began with this code which works perfectly.
AddFood.gs
// File used
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Sheet used
var sheet = ss.getActiveSheet();
/*
* Main function. Associated to the button
*/
function addFood() {
showFormInSideBarAddFood();
}
/*
* Show a form in a side bar for adding food
*/
function showFormInSideBarAddFood() {
var form = HtmlService.createTemplateFromFile('IndexAddFood').evaluate().setTitle("Add Food");
SpreadsheetApp.getUi().showSidebar(form);
}
function processFormAddFood(formObject) {
sheet.appendRow([
formObject.veggie
]);
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
FormAddFood.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<!-- form -->
<form id="addFoodForm" onsubmit="handleFormSubmitAddFood(this)">
<label for="veggie">Veggie</label><br/>
<input type="text" id="veggie" name="veggie"><br/><br/>
<button type="submit">Submit</button>
</form>
</body>
</html>
JavaScriptAddFood.html
<!-- JavaScriptAddFood.html -->
<script>
/*
* The window will not close when the form is summited
*/
function preventFormSubmitAddFood() {
var formsAddFood = document.querySelectorAll('FormAddFood');
for (var i; i < formsAddFood.length; i++) {
formsAddFood[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
// The page is not refreshed when the button submit is pressed
window.addEventListener('load', preventFormSubmit);
/*
* Calls the form
*/
function handleFormSubmitAddFood(formObject) {
google.script.run.processFormAddFood(formObject);
document.getElementById("addFoodForm").reset();
}
</script>
IndexAddFood.html
<!-- IndexAddFood.html -->
<!-- Links the JavaScript file and the HTML forms -->
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Form Add Fruit</title>
<?!= include('JavaScriptAddFood'); ?>
</head>
<body>
<?!= include('FormAddFood'); ?>
</body>
</html>
At this point, I can add the inputbox value in the sheet.
(Don't forget to assign the "addFood" function to a button for tests)
After that, I spent some hours trying to resolve these two issues, following different tutorials :
Add in the same row the fruit and cake dropdown values (Get the dropdown values and add them to the row)
Get the values and display them in an alert box
(Get the html value for displaying it in an alert)
Here's my modified code (which doesn't work):
AddFood.gs
// File used
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Sheet used
var sheet = ss.getActiveSheet();
/*
* Main function. Associated to the button
*/
function addFood() {
showFormInSideBarAddFood();
}
/*
* Show a form in a side bar for adding food
*/
function showFormInSideBarAddFood() {
var form = HtmlService.createTemplateFromFile('IndexAddFood').evaluate().setTitle("Add Food");
SpreadsheetApp.getUi().showSidebar(form);
}
function processFormAddFood(formObject) {
sheet.appendRow([
formObject.veggie,
// Add the dropdown values
selectedFruit,
selectedCake
]);
SpreadsheetApp.getUi().alert(formObject.veggie + ' ' + selectedFruit + ' ' + selectedCake + "added");
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
// Get the value for the alert
function doGet() {
return HtmlService.createHtmlOutputFromFile('FormFood');
}
function getSelectDatas(form) {
var nameBox = form.fruit;
SpreadSheetApp.getUi().alert(nameBox);
}
FormAddFood
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<!-- form -->
<form id="addFoodForm" onsubmit="handleFormSubmitAddFood(this)">
<label for="veggie">Veggie</label><br/>
<input type="text" id="veggie" name="veggie"><br/><br/>
<label for="fruit">Fruit</label><br/>
<select name="fruit" id="fruit" value="" onChange="document.getElementById('addFoodForm').submit()">
<option value="Apple"> Apple </option><br/>
<option value="Pear"> Pear </option><br/>
<option value="Banana"> Banana </option><br/>
</select><br/><br/>
<label for="cake">Cake</label><br/>
<select multiple name="cake" id="cake" value="" onChange="document.getElementById('addFoodForm').submit()">
<option value="crumble"> Crumble </option><br/>
<option value="brownie"> Brownie </option><br/>
<option value="cheeseCake"> Cheese Cake </option><br/>
</select><br/><br/>
<button type="button" value="Submit" onClick="formSubmit()">Submit</button>
</form>
<script>
/**
* Allows to select multiple option in a select form without ctrl + click
*/
var multiSelect = {};
function init() {
var s = document.getElementsByTagName('select');
for (var i = 0; i < s.length; i++) {
if (s[i].multiple) {
var n = s[i].name;
multiSelect[n] = [];
for (var j = 0; j < s[i].options.length; j++) {
multiSelect[n][j] = s[i].options[j].selected;
}
s[i].onchange = changeMultiSelect;
}
}
}
function changeMultiSelect() {
var n = this.name;
for (var i=0; i < this.options.length; i++) {
if (this.options[i].selected) {
multiSelect[n][i] = !multiSelect[n][i];
}
this.options[i].selected = multiSelect[n][i];
}
}
window.onload = init;
</script>
</body>
</html>
JavaScriptAddFood.html
<!-- JavaScriptAddFood.html -->
<script>
/*
* The window will not close when the form is summited
*/
function preventFormSubmitAddFood() {
var formsAddFood = document.querySelectorAll('FormAddFood');
for (var i; i < formsAddFood.length; i++) {
formsAddFood[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
// The page is not refreshed when the button submit is pressed
window.addEventListener('load', preventFormSubmit);
/*
* Calls the form
*/
function handleFormSubmitAddFood(formObject) {
google.script.run.processFormAddFood(formObject);
document.getElementById("addFoodForm").reset();
}
function formSubmit() {
var fruitDropdown = document.getElementById("fruit");
var selectedFruit = e.value;
var cakeDropdown = document.getElementById("fruit");
var selectedCake = e.value;
google.script.run.getSelectDatas(document.forms[0]);
}
</script>
No changes in the file IndexAddFood.html
How could I do to resolve these issues ?
I hope I made myself clear.
Solution
Problem 1
In the processFormAddFood, add the values to the input array that uses appendRow. Use concat to join the first two elements (veggie and fruit) to the possible array (cake).
var rowValues = [formObject.veggie, formObject.fruit].concat(formObject.cake)
sheet.appendRow(rowValues);
Modify the form of FormAddFood.html in the following way:
<!-- form -->
<form id="addFoodForm" onsubmit="handleFormSubmitAddFood(this)">
<label for="veggie">Veggie</label><br/>
<input type="text" id="veggie" name="veggie"><br/><br/>
<label for="fruit">Fruit</label><br/>
<select name="fruit" id="fruit">
<option value="Apple"> Apple </option><br/>
<option value="Pear"> Pear </option><br/>
<option value="Banana"> Banana </option><br/>
</select><br/><br/>
<label for="cake">Cake</label><br/>
<select multiple name="cake" id="cake">
<option value="crumble"> Crumble </option><br/>
<option value="brownie"> Brownie </option><br/>
<option value="cheeseCake"> Cheese Cake </option><br/>
</select><br/><br/>
<button type="submit">Submit</button>
</form>
Problem 2
Check how to display Alert dialogs. Add the following code at the end of processFormAddFood.
var ui = SpreadsheetApp.getUi(); // Same variations.
var result = ui.alert(
'Values entered:',
rowValues.join(', '),
ui.ButtonSet.OK);
Related
I'm new to the scripting, but from what I have learned from this website, I have put together a check book balancesheet in google sheets.
I have a function "AddCheck" attached to the button on one of the cell. What it does is - opens a dialog box where I enter check details, like Date, Invoice number, amount and vendor's name. Then I click the submit button and Google sheets creates a row and adds those values.
My Question is how do I add a button next to the submit button that will allow me to add the New check details without leaving the dialog box. So that it will add the values to the cells and will clear the dialog box for another Entry.
This is my AddCheck function
function AddCheck() {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('3:3').activate();
spreadsheet.getActiveSheet().insertRowsBefore(spreadsheet.getActiveRange().getRow(), 1);
spreadsheet.getActiveRange().offset(0, 0, 1, spreadsheet.getActiveRange().getNumColumns()).activate();
spreadsheet.getRange('A3').activate();
spreadsheet.getCurrentCell().setFormula('=A4+1');
spreadsheet.getRange('G3').activate();
spreadsheet.getCurrentCell().setValue('Pending');
spreadsheet.getRange('B3').activate();
fncOpenMyDialog()
};
This is my HTML dialog file
<!DOCTYPE html>
<html>
<body>
<form>
<label for="Date">Date :</label>
<input type='date' name='Date' id="Date" required="required"/>
<br>
<label for="Invoice">Invoice</label>
<input type='text' name='Invoice' id="Invoice" required="required"/>
<label for="Amount">Amount</label>
<input type='text' name='Amount' id="Amount" required="required"/>
<label for="Company">Company</label>
<select name="Class" id="vendor-selector" autofocus="autofocus" autocorrect="off" autocomplete="off">
<script>
(function () {
google.script.run.withSuccessHandler(
function (selectList) {
var select = document.getElementById("vendor-selector");
for( var i=0; i<selectList.length; i++ ) {
var option = document.createElement("option");
option.text = selectList[i][0];
select.add(option);
}
}
).getSelectList();
}());
</script>
</select>
<input type="submit" value="Submit" onclick="myFunction(this.parentNode)">
</form>
<p id="CompanyName"></p>
<script>
function myFunction(obj) {
var x = document.getElementById("vendor-selector").value;
document.getElementById("CompanyName").innerHTML = x;
google.script.run
.withSuccessHandler(() => google.script.host.close())
.functionToRunOnFormSubmit(obj);
}
</script>
</body>
</html>
This Function calls the Dialog
function fncOpenMyDialog() {
//Open a dialog
var htmlDlg = HtmlService.createHtmlOutputFromFile('CheckDetails')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(200)
.setHeight(250);
SpreadsheetApp.getUi()
.showModalDialog(htmlDlg, 'Check Details');
};
function functionToRunOnFormSubmit(fromInputForm) {
Logger.log(fromInputForm);
var ss = SpreadsheetApp.getActive();
ss.getSheetByName("Checks").getRange(3,3).setValues([[fromInputForm.Class]]);
ss.getSheetByName("Checks").getRange(3,2).setValues([[fromInputForm.Date]]);
ss.getSheetByName("Checks").getRange(3,4).setValues([[fromInputForm.Invoice]]);
ss.getSheetByName("Checks").getRange(3,6).setValues([[fromInputForm.Amount]]);
};
and this Function gets the List of vendors from Sheet2
function getSelectList()
{
var sheet = SpreadsheetApp.openById("141mlnxJBjepKxYCGXHFhz5IIEVnp6T2DDsb_uRgnZzY").getSheetByName('Sheet2');
var lastRow = sheet.getLastRow();
var myRange = sheet.getRange("A2:A" + lastRow);
var data = myRange.getValues();
Logger.log("Data = " + data);
return data;
};
function doGet()
{
return HtmlService.createHtmlOutputFromFile('CheckDetails');
}
Thank you for your help.
In order to implement this "Submit & Continue" feature, you only need to change the front-end code so that:
There is a new button.
Upon clicking the new button, the same back-end (GAS) code gets executed.
The dialog does not get closed after the GAS code execution, but the input elements are reset.
Code modifications
Add an id to the form tag so that it may be easily selected.
<form id="CheckDetailsForm">
Create a "Submit & Continue" button in your HTML. Assign an id to it so that it may be easily selected.
<input type="submit" value="Submit and continue" id="SubmitAndContinueInput" />
Within the script tag, add an event listener to the newly created button.
document.getElementById("SubmitAndContinueInput").addEventListener("click", myFunctionContinue);
Add the handler function for the newly created button's onclick event. This function will be very similar as the one you are using but: It will use the preventDefault to avoid the form being incorrectly sent and will clear the form data upon submission.
function clearForm() {
document.getElementById('Date').value = "";
document.getElementById('Invoice').value = "";
document.getElementById('Amount').value = "";
}
function myFunctionContinue(e) {
e.preventDefault();
var obj = document.getElementById("CheckDetailsForm");
var x = document.getElementById("vendor-selector").value;
document.getElementById("CompanyName").innerHTML = x;
google.script.run
.withSuccessHandler(clearForm)
.functionToRunOnFormSubmit(obj);
}
Example dialog:
Edit
Handling "submit and continue" new rows:
Remove the row-insertion functionality from AddCheck(). We will handle this logic afterwards:
function AddCheck() {
fncOpenMyDialog();
}
Modify the functionToRunOnFormSubmit() function so that it handles the row-insertion logic. I have also cleaned up the code a little bit. It would look like the following:
function functionToRunOnFormSubmit(fromInputForm) {
Logger.log(fromInputForm);
var sheet = SpreadsheetApp.getActive().getSheetByName("Checks");
sheet.insertRowBefore(3);
sheet.getRange("A3").setFormula("=A4+1");
sheet.getRange("B3").setValue(fromInputForm.Date);
sheet.getRange("C3").setValue(fromInputForm.Class);
sheet.getRange("D3").setValue(fromInputForm.Invoice);
sheet.getRange("F3").setValue(fromInputForm.Amount);
sheet.getRange("G3").setValue("Pending");
}
Full code
CheckDetails.html
<!DOCTYPE html>
<html>
<body>
<form id="CheckDetailsForm">
<label for="Date">Date :</label>
<input type='date' name='Date' id="Date" required="required"/>
<br>
<label for="Invoice">Invoice</label>
<input type='text' name='Invoice' id="Invoice" required="required"/>
<label for="Amount">Amount</label>
<input type='text' name='Amount' id="Amount" required="required"/>
<label for="Company">Company</label>
<select name="Class" id="vendor-selector" autofocus="autofocus" autocorrect="off" autocomplete="off">
<script>
(function () {
google.script.run.withSuccessHandler(
function (selectList) {
var select = document.getElementById("vendor-selector");
for( var i=0; i<selectList.length; i++ ) {
var option = document.createElement("option");
option.text = selectList[i][0];
select.add(option);
}
}
).getSelectList();
}());
</script>
</select>
<input type="submit" value="Submit" id="SubmitInput" />
<input type="submit" value="Submit and continue" id="SubmitAndContinueInput" />
</form>
<p id="CompanyName"></p>
<script>
document.getElementById("SubmitInput").addEventListener("click", myFunction);
document.getElementById("SubmitAndContinueInput").addEventListener("click", myFunctionContinue);
function clearForm() {
document.getElementById('Date').value = "";
document.getElementById('Invoice').value = "";
document.getElementById('Amount').value = "";
}
function myFunction(e) {
e.preventDefault();
var obj = document.getElementById("CheckDetailsForm");
var x = document.getElementById("vendor-selector").value;
document.getElementById("CompanyName").innerHTML = x;
google.script.run
.withSuccessHandler(() => google.script.host.close())
.functionToRunOnFormSubmit(obj);
}
function myFunctionContinue(e) {
e.preventDefault();
var obj = document.getElementById("CheckDetailsForm");
var x = document.getElementById("vendor-selector").value;
document.getElementById("CompanyName").innerHTML = x;
google.script.run
.withSuccessHandler(clearForm)
.functionToRunOnFormSubmit(obj);
}
</script>
</body>
</html>
Code.gs
function AddCheck() {
fncOpenMyDialog()
}
function fncOpenMyDialog() {
//Open a dialog
var htmlDlg = HtmlService.createHtmlOutputFromFile('CheckDetails')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(200)
.setHeight(250);
SpreadsheetApp.getUi()
.showModalDialog(htmlDlg, 'Check Details');
}
function functionToRunOnFormSubmit(fromInputForm) {
Logger.log(fromInputForm);
var sheet = SpreadsheetApp.getActive().getSheetByName("Checks");
sheet.insertRowBefore(3);
sheet.getRange("A3").setFormula("=A4+1");
sheet.getRange("B3").setValue(fromInputForm.Date);
sheet.getRange("C3").setValue(fromInputForm.Class);
sheet.getRange("D3").setValue(fromInputForm.Invoice);
sheet.getRange("F3").setValue(fromInputForm.Amount);
sheet.getRange("G3").setValue("Pending");
}
function getSelectList() {
var sheet = SpreadsheetApp.openById("141mlnxJBjepKxYCGXHFhz5IIEVnp6T2DDsb_uRgnZzY").getSheetByName('Sheet2');
var lastRow = sheet.getLastRow();
var myRange = sheet.getRange("A2:A" + lastRow);
var data = myRange.getValues();
Logger.log("Data = " + data);
return data;
}
function doGet() {
return HtmlService.createHtmlOutputFromFile('CheckDetails');
}
I really need help I almost finish my google script but I am in trouble I do not how to get the selected option(month selected) from the downlist (html) and storage in a "var", I really appreciate your help.
I tried with getElementById without success.
Thank You.
Document Code.gs
/*** Retrieves all the rows in the active spreadsheet that contain data and logs the values for each row.
* For more information on using the Spreadsheet API, see
* https://developers.google.com/apps-script/service_spreadsheet*/
function Menu() {
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.createMenu("Christian's Menu")
.addItem('Side Bar Comites', 'showSidebar')
.addToUi();
}
function showSidebar() {
var html = HtmlService.createHtmlOutputFromFile('Page')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle('Sedesol - Captura de Entregas')
.setWidth(250);
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.showSidebar(html);
}
function autowritemonthday(form){
var storeMonth = getElementById('monthlist').value; /*Does not work i dont know why*/
Browser.msgBox(storeMonth); /*tried to view the value from var storeMonth*/
/*I put this as comment because does not work either
var e = document.getElementById('monthlist');
var val = e.options[e.selectedIndex].text;*/
/*I need Storage the selected value from the downlist here before the onSeach(form)*/
onSearch(form); /*call the function to search the input text and put the cursor in the right Cell*/
var hoja = SpreadsheetApp.getActiveSpreadsheet();
var sheet = hoja.getSheets()[0];
var rows = sheet.getDataRange();
var ss = hoja.getActiveCell()
var selectedrow = ss.getRow();
var selectedcol = ss.getColumn();
var monthpos = sheet.getRange(selectedrow, 7); /* get the cell position for example monthpost(5,7)*/
var daypos = sheet.getRange(selectedrow, 8);
var tempm = form.mesinini; /*get the value of the inputbox by NAME*/
var tempd = form.dias;
var remspacestxtmonth = tempm.trim(); /*remove blank spaces*/
var uppertxtmonth = remspacestxtmonth.toUpperCase();/*conv. to uppercase*/
var remspacestxtday = tempd.trim(); /*remove blank spaces*/
monthpos.setValue(uppertxtmonth); /*write the var value in the selected cell preview positioned by the function onSearch*/
daypos.setValue(remspacestxtday);
}
function doGet() {
return HtmlService.createHtmlOutputFromFile("Page");
}
function onSearch(form){
var tempc = form.comites;
var comite = tempc.trim();
/*Browser.msgBox(comite);*/
var searchString = comite;
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("REYNOSA");
var column =4; //column Index - where i am going to search the value of the var comite
var columnValues = sheet.getRange(2, column, sheet.getLastRow()).getValues(); //1st cell Titles
var searchResult = columnValues.findIndex(searchString); //Cell Index - 2
if(searchResult != -1)
{
//searchResult + 2 is row index.
SpreadsheetApp.getActiveSpreadsheet().setActiveRange(sheet.getRange(searchResult + 2, 1))
}
}
Array.prototype.findIndex = function(search){
if(search == "") return false;
for (var i=0; i<this.length; i++)
if (this[i] == search) return i;
return -1;
}
Array.prototype.findIndex = function(search){
if(search == "") return false;
for (var i=0; i<this.length; i++)
if (this[i] == search) return i;
return -1;
}
page.html
<head>
<title>Page</title>
</head>
<body>
<div>
<form>
INGRESA LA FECHA DE ENTREGA QUE DESEAS UTILIZAR PARA LOS COMITES... /EN/...WRITE THE DATE YOU ARE GOING TO USE TO CAPTURE THE RECEIPTS
<br><br/>
<select id="monthlist" name="monthlist">
<option value="enero">JANUARY</option>
<option value="febrero">FEBRUARY</option>
<option value="marzo">MARCH</option>
<option value="abril">APRIL</option>
<option value="mayo">MAY</option>
<option value="Junio">JUNE</option>
<option value="julio">JULY</option>
<option value="agosto">AUGUST</option>
<option value="septiembre">SEPTEMBER</option>
<option value="octubre">OCTOBER</option>
<option value="noviembre">NOVEMBER</option>
<option value="diciembre">DECEMBER</option>
</select>
<br><br/>
Ingresa el MES [EJEMPLO: MARZO]: /EN/WRITE THE MONTH <input id="resp" type="text" value="" name="mesinini" />
<br><br/>
Ingresa el DIA /EN/WRITE THE DAY OF THE MONTH [EJEMPLO: 14]: <input id="resp" type="text" value="" name="dias" />
<br><br/>
CAPTURA EL COMITE. /EN/ CAPTURE THE RECEIPT NUMBER
<br><br/>
Ingresa el Comite: /EN/ WRITE THE RECEIPT NUMBER <input id="resp" type="text" value="" name="comites" />
<br><br/>
<input type="button" onclick="formautomd()" value="Capturar Entrega del Comite"/> /*THIS BUTTON*/
<br><br/>
<input type="button" onclick="formonSearch()" value="Buscar Comite"/>
<br><br/>
<input type="button" onclick="formexit()" value="Salir del Menu"/>
</form>
</div>
</body>
<script type="text/javascript">
function formonSearch() {
/////even tried to put the getElementbyId here and same result.
google.script.run.onSearch(document.forms[0]);
}
function formautomd() {
google.script.run.autowritemonthday(document.forms[0]);
} /* IT NEED BE STORAGED WHEN I PRESS THIS BUTTON*/
function formexit(){
google.script.host.close();
}
</script>
getElementById() can not be used in .gs server code. The .gs script runs on Google's servers. getElementById() only works in the browser. Your function:
function autowritemonthday(form){
var storeMonth = getElementById('monthlist').value;
/*Does not work i dont know why*/
Is in the .gs code. getElementById() only works in a <script> tag in HTML.
The data you want must come from the 'form' object.
This is what you need to use:
var storeMonth = form["monthlist"];
To see what is in your form object, iterate through the form object like this:
function autowritemonthday(form){
Logger.log('form: ' + form);
for (var key in form) {
Logger.log('the key is: ' + key);
Logger.log('the value is: ' + form[key]);
};
return;
};
Submit the form, then in the code editor, choose the VIEW menu, and then LOGS.
My original answer:
Did you try something like this:
function formautomyd() {
var storeMonth = getElementById('monthlist').value;
google.script.run.autofechaydia(document.forms[0]);
}
You stated that you used:
getElementByID
But didn't show the code. The letter "D" on the end can't be capitalized. Must be lower case. getElementById()
I have a form that only captures following fields.(see below) I need to revise it, so that field "formdesc" (form description) captures what was selected in the dropdown as text only. But now there is an options id = [0, 1, 2,3] that are used for price point in JS to calculate total ammount purchased.
HTML:
<form action="http://" method="get" name="form">
<input id="forminv" type="hidden" name="forminv" value="StudentOrg"> (fixed value)
<input id="formbal" type="hidden" name="formbal" value="0"> (this pulls total from id=tot)
<input type="text" name="formfname"> (this pulls first name)
<input type="text" name="formlname"> (this pulls last name)
<type="text" name="formid"> (this for a student number)
<select id="apparelType" name="formdesc"> (this should pull value from selection)
<option selected value="na">Select</option>
<option value="0">T-Shirt</option> (I need to change this value to “shirt”)
<option value="1">Shorts</option> (here too, but can't work with JS below)
<option value="2">Hat</option> (here too)
<option value="3">Bag</option> (here too)
<input id="numb" type="number" name="formterm"> (this pulls quantity, and changes total)
<id="tot"<Total: $0.00 >
<input type="submit" value=" Make a Credit Card Payment">
</form>
JS:
$(document).ready(function () {
$('#numb').keyup(function () {
var appVal = new Array();
appVal[0] = 15; (if I change this, stops working)
appVal[1] = 20;
appVal[2] = 25;
appVal[3] = 30;
var cost = 0;
var fmapVal = $('#apparelType').val();
if (fmapVal == 'na') {
alert('Please select an apparel type.');
} else {
cost = appVal[fmapVal];
};
//alert(cost);
var getNumb = $('#numb').val();
var baseTotal = cost * getNumb;
var getTax = baseTotal * .06;
var getTotal = baseTotal + getTax;
$('#tot').html('Total: $' + etTotal.toFixed(2));
$('#formbal').val(getTotal.toFixed(2));
});
});
Here is working fiddle
change $('#tot').html() to $('#tot').val()
If you require the selected items text, then use;
var txt = $('#apparelType').find('option:selected').text();
i'm developing a meta search engine website, Soogle and i've used JS to populate select menu..
Now, after the page is loaded none of engines is loaded by default, user needs to select it on his own or [TAB] to it..
Is there a possibility to preselect one value from the menu via JS after the page loads?
This is the code:
Javascript:
// SEARCH FORM INIT
function addOptions(){
var sel=document.searchForm.whichEngine;
for(var i=0,l=arr.length;i<l;i++){
sel.options[i]=new Option(arr[i][0], i);
}
}
function startSearch(){
var searchString=document.searchForm.searchText.value;
if(searchString.replace(/\s+/g,"").length > 0){
var searchEngine=document.searchForm.whichEngine.selectedIndex,
finalSearchString=arr[searchEngine][1]+searchString;
window.location=finalSearchString;
}
return false;
}
function checkKey(e){
var key = e.which ? e.which : event.keyCode;
if(key === 13){
return startSearch();
}
}
// SEARCH ENGINES INIT
var arr = [
["Web", "http://www.google.com/search?q="],
["Images", "http://images.google.com/images?q="],
["Knowledge","http://en.wikipedia.org/wiki/Special:Search?search="],
["Videos","http://www.youtube.com/results?search_query="],
["Movies", "http://www.imdb.com/find?q="],
["Torrents", "http://thepiratebay.org/search/"]
];
HTML:
<body onload="addOptions();document.forms.searchForm.searchText.focus()">
<div id="wrapper">
<div id="logo"></div>
<form name="searchForm" method="POST" action="javascript:void(0)">
<input name="searchText" type="text" onkeypress="checkKey(event);"/>
<span id="color"></span>
<select tabindex="1" name="whichEngine" selected="Web"></select>
<br />
<input tabindex="2" type="button" onClick="return startSearch()" value="Search"/>
</form>
</div>
</body>
I appreciate that your question asks for a solution that utilises JavaScript, but having looked at the webpage in question I feel confident in making this point:
Your problem is that you are trying to use JavaScript for something that HTML itself was designed to solve:
<select name="whichEngine">
<option value="http://www.google.com/search?q=" selected="selected">Web</option>
<option value="http://images.google.com/images?q=">Images</option>
<option value="http://en.wikipedia.org/wiki/Special:Search?search=">Knowledge</option>
<option value="http://www.youtube.com/results?search_query=">Videos</option>
<option value="http://www.imdb.com/find?q=">Movies</option>
<option value="http://thepiratebay.org/search/">Torrents</option>
</select>
Fear not, though! You can still access all of the options from JavaScript in the same way that you did before.
function alertSelectedEngine() {
var e = document.getElementsByName("whichEngine")[0];
alert("The user has selected: "+e.options[e.selectedIndex].text+" ("+e.options[e.selectedIndex].value+")");
}
Please, forgive and listen to me.
I have modified the code to use jQuery. It is working fine in IE8, IE8 (Compatibility mode) and in FireFox.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Index</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
// SEARCH ENGINES INIT
var arr = new Array();
arr[arr.length] = new Array("Web", "http://www.google.com/search?q=");
arr[arr.length] = new Array("Images", "http://images.google.com/images?q=");
arr[arr.length] = new Array("Knoweledge", "http://en.wikipedia.org/wiki/Special:Search?search=");
arr[arr.length] = new Array("Videos", "http://www.youtube.com/results?search_query=");
arr[arr.length] = new Array("Movies", "http://www.imdb.com/find?q=");
arr[arr.length] = new Array("Torrents", "http://thepiratebay.org/search/");
// SEARCH FORM INIT
function addOptions() {
// Add the options to the select dropdown.
var nOptions = arr.length;
var optionText = '';
for (var i = 0; i < nOptions; i++) {
optionText += '<option value="' + i + '">' + arr[i][0] + '</option>'
}
//alert('optionText = ' + optionText);
// Add the options to the select drop down.
$('select#whichEngine').html(optionText);
// set the second option as default. This can be changed, if required.
$('select#whichEngine option:eq(1)').attr('selected', true);
}
function startSearch() {
var searchEngineIndex = $('select#whichEngine option:selected').attr('value');
searchEngineIndex = parseInt(searchEngineIndex, 10);
var searchString = $('input#searchText').val();
if (searchEngineIndex >= 0 && searchString) {
var searchURL = arr[searchEngineIndex][1] + searchString;
//alert('location = ' + searchURL);
window.location.href = searchURL;
}
return false;
}
function checkKey(e) {
var character = (e.which) ? e.which : event.keyCode;
if (character == '13') {
return startSearch();
}
}
$(function() {
// Add the options to the select drop down.
addOptions();
// Add focus to the search text box.
$('input#searchText').focus();
// Hook the click event handler to the search button.
$('input[type=button]').click(startSearch);
$('input#searchText').keyup(checkKey);
});
</script>
</head>
<body>
<div id="wrapper">
<div id="logo"></div>
<form name="searchForm" method="POST" action="javascript:void(0)">
<input id="searchText" name="searchText" type="text"/>
<span id="color"></span>
<select tabindex="1" id="whichEngine" name="whichEngine"></select>
<br />
<input tabindex="2" type="button"value="Search"/>
</form>
</div>
</body>
</html>
You had some errors in how you handle the <select> values and options. I would reorganize your JavaScript like this:
// SEARCH ENGINES
var arr = [["Web", "http://www.google.com/search?q="],
["Images", "http://images.google.com/images?q="],
["Knowledge", "http://en.wikipedia.org/wiki/Special:Search?search="],
["Videos", "http://www.youtube.com/results?search_query="],
["Movies", "http://www.imdb.com/find?q="],
["Torrents", "http://thepiratebay.org/search/"]];
// SEARCH FORM INIT
function addOptions(){
var sel=document.searchForm.whichEngine;
for(var i=0;i<arr.length;i++) {
sel.options[i]=new Option(arr[i][0],arr[i][1]);
}
}
function startSearch(){
var searchString = document.searchForm.searchText.value;
if(searchString!==''){
var mySel = document.searchForm.whichEngine;
var finalLocation = mySel.options[mySel.selectedIndex].value;
finalLocation += encodeURIComponent(searchString);
location.href = finalLocation;
}
return false;
}
function checkKey(e){
var character=(e.which) ? e.which : event.keyCode;
return (character=='13') ? startSearch() : null;
}
I would also move your onload handler into the main body of your JavaScript:
window.onload = function() {
addOptions();
document.searchForm.searchText.focus();
};
I also made some changes to your HTML:
<body>
<div id="wrapper">
<div id="logo"></div>
<form name="searchForm" method="POST" action="." onsubmit="return false;">
<input name="searchText" type="text" onkeypress="checkKey(event);" />
<span id="color"></span>
<select tabindex="1" name="whichEngine" selected="Web"></select><br />
<input tabindex="2" type="button" value="Search"
onclick="startSearch();" />
</form>
</div>
</body>
You could specify which egine you would like preselected in the engines array like this:
// SEARCH ENGINES INIT
// I've used array literals for brevity
var arr = [
["Web", "http://www.google.com/search?q="],
["Images", "http://images.google.com/images?q="],
["Knoweledge", "http://en.wikipedia.org/wiki/Special:Search?search="],
/*
* notice that this next line has an extra element which is set to true
* this is my default
*/
["Videos", "http://www.youtube.com/results?search_query=", true],
["Movies", "http://www.imdb.com/find?q="],
["Torrents", "http://thepiratebay.org/search/"]
];
Then in your setup function:
// SEARCH FORM INIT
function addOptions() {
var sel = document.searchForm.whichEngine;
for (var i = 0; i < arr.length; i++) {
// notice the extra third argument to the Option constructor
sel.options[i] = new Option( arr[i][0], i, arr[i][2] );
}
}
if your only concern is preselecting an engine onload, don't "over-engineer" it.
var Web = "http://www.google.com/search?q=";
var Images = "http://images.google.com/images?q=";
var Knowledge = "http://en.wikipedia.org/wiki/Special:Search?search=";
var Videos = "http://www.youtube.com/results?search_query=";
var Movies = "http://www.imdb.com/find?q=";
var Torrents = "http://thepiratebay.org/search/";
function addOptions(source){
var sel=document.searchForm.whichEngine;
for(var i=0,l=arr.length;i<l;i++){
sel.options[i]=new Option(arr[i][0], i);
}
}
then insert your argument made onto your body tag to a pre-defined variable. If you want something random, create a new function with your equation for selecting a random variable then load your addOptions(function) within your new function. Then remove addOptions from your body tag.
<body onload="addOptions(Web);document.forms.searchForm.searchText.focus()">
I would like help to manipulate to following javascript code so that there are buttons instead of the first drop-down-menu have buttons to choose the values of the next set of values for the drop-down-menus.
The code is:
<html>
<head><title>JS example</title></head>
<body>
<script type="text/javascript"><!--
//
var opt_one = new Array('blue', 'green', 'red');
var opt_two = new Array('plaid', 'paisley', 'stripes');
//
function updateTarget() {
var f = document.myform;
var which_r = null;
if (f) {
// first option selected? ("One")
if (f.trigger.value == '1') {
which_r = opt_one;
// ...or, second option selected? ("Two")
} else if (f.trigger.value == '2') {
which_r = opt_two;
// no known option, hide the secondary popup
} else {
f.target.style.display = 'none';
}
// did we find secondary options for the selection?
if (which_r) {
// reset/clear the target pop-up
f.target.innerHTML = '';
// add each option
for (var opt in which_r) {
f.target.innerHTML += '<option>' + which_r[opt] + '</option>';
}
// display the secondary pop-up
f.target.style.display = 'inline';
}
}
} // updateTarget()
//-->
</script>
<form name="myform" action="#">
<select name="trigger" onchange="updateTarget();">
<option>Select one...</option>
<option>-</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
<select name="target" style="display:none;">
</select>
</form>
</body>
</html>
So what I am trying to do is make it that the words 'ONE' and 'TWO' instead of being in a drop-down-menu, be buttons. So that when it is cliked it brings up their specified array.
Thank you in advance!
If I understand your question correctly this should work.
<html>
<head><title>JS example</title></head>
<body>
<script type="text/javascript"><!--
//
var opt_one = new Array('blue', 'green', 'red');
var opt_two = new Array('plaid', 'paisley', 'stripes');
//
function updateTarget(button) {
var f = document.myform;
var which_r = null;
if (f) {
// first option selected? ("One")
if (button.name == 'one') {
which_r = opt_one;
// ...or, second option selected? ("Two")
} else if (button.name == 'two') {
which_r = opt_two;
// no known option, hide the secondary popup
} else {
f.target.style.display = 'none';
}
// did we find secondary options for the selection?
if (which_r) {
// reset/clear the target pop-up
f.target.innerHTML = '';
// add each option
for (var opt in which_r) {
f.target.innerHTML += '<option>' + which_r[opt] + '</option>';
}
// display the secondary pop-up
f.target.style.display = 'inline';
}
}
} // updateTarget()
//-->
</script>
<form name="myform" action="#">
<input name="one" type="button" onclick="updateTarget(this)" value="One"/> <input name="two" type="button" onclick="updateTarget(this)" value="Two"/>
<select name="target" style="display:none;">
</select>
</form>
</body>
</html>
You could simply create two buttons and invoke the updateTarget() function in the onClick event of the buttons :
<input type="button" value="Option 1" onclick="updateTarget(1);" />
<input type="button" value="Option 2" onclick="updateTarget(2);" />
Note that the signature of the updateTarget() must change to allow you to pass the parameter so that your code can branch accordingly:
function updateTarget(optionNumber)
{
if (optionNumber == 1)
...
else if (optionNumber == 2)
...
else
...
}