Please I want to output a variable from js to an html tag so i can see the results in a specific place on my page. here is the code:
<script type="text/javascript">
function doMath()
{
// Capture the entered values of two input boxes
var my_input1 = document.getElementById('my_input1').value;
var my_input2 = document.getElementById('my_input2').value;
var my_input3 = document.getElementById("my_input3").value;
var my_input4 = document.getElementById("my_input4").value;
//alert(form.elements["my_input2"].value);
//var my_input3 = document.getElementById('my_input3').value;
// Add them together and display
var sum = parseInt(my_input1) / parseInt(my_input2) * parseInt(my_input3) * parseInt(my_input4);
document.write(sum);
}
Let us say you want to display the response in a div with id sum
<div id="sum"></div>
To do so, update
document.write(sum);
to
document.getElementById("sum").innerHTML = sum;
Related
I have this problem here
The problem has been solved, but my question is how can I get the second value from that, or the third one. The sheet will have many tables and at some point I will need a total for each table. Also, is there any solution to automatically find the the array number which contain date row for each table (instead defining this manually). Hope my explanation make sense.
Thank you!
Kind regards,
L.E. Test file
If I understood your question correctly, instead of breaking the loop when a match to "Total" is found do whatever is needed to be done within the loop like so...
var today = toDateFormat(new Date());
var todaysColumn =
values[5].map(toDateFormat).map(Number).indexOf(+today);
var emailDate = Utilities.formatDate(new Date(today),"GMT+1",
"dd/MM/yyyy");
for (var i=0; i<values.length; i++){
if (values[i][0]=='Total'){
nr = i;
Logger.log(nr);
var output = values[nr][todaysColumn];
// Do something with the output here I"m assuming you email it
}
}
The loop will keep going and find every "Total" and do the same thing. This answer assumes that the "Totals" are in the same column. You can get fancier with this if you only want certain tables to send and not others, but this should get you started.
I didn't quite understand the second part of your question...
"Also, is there any solution to automatically find the the array
number which contain date row for each table (instead defining this
manually). Hope my explanation make sense."
I'm guessing you want all the rows that contain "Total" in the specific column. You could instantiate a variable as an empty array like so, var totals = [];. Then instead of sending the email or whatever in the first loop you would push the row values to the array like so, totals.push(nr+1) . //adding 1 gives you the actual row number (rows count from 1 but arrays count from 0). You could then simply loop through the totals array and do whatever you wanted to do. Alternatively you could create an array of all the values instead of row numbers like totals.push(values[nr][todaysColumn]) and loop through that array. Lots of ways to solve this problem!
Ok based on our conversation below I've edited the "test" sheet and updated the code. Below are my edits
All edits have been made in your test sheet and verified working in Logger. Let me know if you have any questions.
Spreadsheet:
Added "Validation" Tab
Edited "Table" tab so the row with "Email Address" in Column A lines up with the desired lookup values (dates or categories)...this was only for the first two tables as all the others already had this criteria.
Code:
Create table/category selector...
In the editor go to File >> New >> HTMLfile
Name the file "inputHTML"
Copy and paste the following code into that file
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form class="notice_form" autocomplete="off" onsubmit="formSubmit(this)" target="hidden_iframe">
<select id="tables" onchange="hideunhideCatagory(this.value)" required></select>
<p></p>
<select id="categories" style="display:none"></select>
<hr/>
<button class="submit" type="submit">Get Total</button>
</form>
<script>
window.addEventListener('load', function() {
console.log('Page is loaded');
});
</script>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
// The code in this function runs when the page is loaded.
$(function() {
var tableRunner = google.script.run.withSuccessHandler(buildTableList);
var catagoryRunner = google.script.run.withSuccessHandler(buildCatagoryList);
tableRunner.getTables();
catagoryRunner.getCategories();
});
function buildTableList(tables) {
var list = $('#tables');
list.empty();
list.append('<option></option>');
for (var i = 0; i < tables.length; i++) {
if(tables[i]==''){break;}
list.append('<option>' + tables[i] + '</option>');
}
}
function buildCatagoryList(categories) {
var list = $('#categories');
list.empty();
list.append('<option></option>');
for (var i = 0; i < categories.length; i++) {
if(categories[i]==''){break;}
list.append('<option>' + categories[i] + '</option>');
}
}
function hideunhideCatagory(tableValue){
var catElem = document.getElementById("categories");
if(tableValue == "Total Calls By Date" || tableValue == "Total Appointments by Date"){
catElem.style.display = "none"
document.required = false;
}else{
catElem.style.display = "block"
document.required = true;
}
}
function formSubmit(argTheFormElement) {
var table = $("select[id=tables]").val(),
catagory = $("select[id=categories]").val();
console.log(table)
google.script.run
.withSuccessHandler(google.script.host.close)
.getTotal(table,catagory);
}
</script>
</body>
<div id="hiframe" style="display:block; visibility:hidden; float:right">
<iframe name="hidden_iframe" height="0px" width="0px" ></iframe>
</div>
</html>
Edits to Code.gs file
Replace code in Code.gs with this...
//This is a simple trigger that creates the menu item in your sheet
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Run Scripts Manually')
.addItem('Get Total','fncOpenMyDialog')
.addToUi();
}
//This function launches the dialog and is launched by the menu item
function fncOpenMyDialog() {
//Open a dialog
var htmlDlg = HtmlService.createHtmlOutputFromFile('inputHTML')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(200)
.setHeight(150);
SpreadsheetApp.getUi()
.showModalDialog(htmlDlg, 'Select table to get total for');
};
//main function called by clicking "Get Total" on the dialogue...variables are passed to this function from the formSubmit in the inputHTML javascript
function getTotal(table,catagory) {
function toDateFormat(date) {
try {return date.setHours(0,0,0,0);}
catch(e) {return;}
}
//get all values
var values = SpreadsheetApp
.openById("10pB0jDPG8HYolECQ3eg1lrOFjXQ6JRFwQ-llvdE2yuM")
.getSheetByName("Tables")
.getDataRange()
.getValues();
//declare/instantiate your variables
var tableHeaderRow, totalRow, tableFound = false;
//begin loop through column A in Tables Sheet
for (var i = 0; i<values.length; i++){
//test to see if values have already been found if so break the loop
if(tableFound == true){break;}
//check to see if value matches selected table
if (values[i][0]==table){
//start another loop immediately after the match row
for(var x=i+1; x<values.length; x++){
if(values[x][0] == "Email Address"){ //This header needs to consistantly denote the row that contains the headers
tableHeaderRow = x;
tableFound = true;
}else if(values[x][0] == "Total"){
totalRow = x;
break;
}
}
}
}
Logger.log("Header Row = "+tableHeaderRow)
Logger.log("Total Row = "+ totalRow)
var today = toDateFormat(new Date())
var columnToTotal;
if(catagory==''){
columnToTotal = values[tableHeaderRow].map(toDateFormat).map(Number).indexOf(+today);
}else{
columnToTotal = values[tableHeaderRow].indexOf(catagory);
}
var output = values[totalRow][columnToTotal];
Logger.log(output);
var emailDate = Utilities.formatDate(new Date(today),"GMT+1", "dd/MM/yyyy");
//here is where you would put your code to do something with the output
}
/** The functions below are used by the form to populate the selects **/
function getTables(){
var cFile = SpreadsheetApp.getActive();
var cSheet = cFile.getSheetByName('Validation');
var cSheetHeader = cSheet.getRange(1,1,cSheet.getLastRow(),cSheet.getLastColumn()).getValues().shift();
var tabelCol = (cSheetHeader.indexOf("Tables")+1);
var tables = cSheet.getRange(2,tabelCol,cSheet.getLastRow(),1).getValues();
return tables.filter(function (elem){
return elem != "";
});
}
function getCatagories(){
var cFile = SpreadsheetApp.getActive();
var cSheet = cFile.getSheetByName('Validation');
var cSheetHeader = cSheet.getRange(1,1,cSheet.getLastRow(),cSheet.getLastColumn()).getValues().shift();
var catagoriesCol = (cSheetHeader.indexOf("Catagory")+1);
var catagories = cSheet.getRange(2,catagoriesCol,cSheet.getLastRow(),1).getValues();
return catagories.filter(function (elem){
return elem != "";
});
}
I am trying to output pictures of words based on the users input , i was wondering if there was a way to do it through Loop through an array and concatenate the HTML for the image elements with src's set to the corresponding image?
//myArray
var Signs = new Array("signa.jpg", "signb.jpg", "signc.jpg", "signd.jpg", "signe.jpg", "signf.jpg", "signg.jpg", "signh.jpg", "signi.jpg", "signj.jpg", "signk.jpg", "signl.jpg", "signm.jpg", "signn.jpg", "signo.jpg", "signp.jpg", "signq.jpg", "signr.jpg", "signs.jpg", "signt.jpg", "signu.jpg", "signv.jpg", "signw.jpg", "signx.jpg", "signy.jpg", "signz.jpg");
$(document).ready(function () {
$("#btnGet").click(function () {
var pattern = new RegExp(/^[a-zA-Z]+$/);
var UserInput;
UserInput = $('#txt_name').val();
//splits input
UserInput = UserInput.split("");
//gets data from input
var userFirstName = trim($("#txt_name").val());
text = text.toLowerCase(); //put all text into lower case
});//end of txt_name
});//end of btnGet
//Trim function from http://www.somacon.com/p355.php
function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g, "");
}
</script>
You can use code such as the following - this generates the html img tag for each letter and then injects these into a DOM element (assuming, for example, you have a div with id of "output":
var imageTags = $('#txt_name').val().split('').map (function(c) {return '<img src="img' + c + '.png" />';}, '');
$("#output").html(imageTags.join(''));
Here is a sample jsFiddle:
http://jsfiddle.net/zdmmx49k/4/
I made the following code to replace form fields in a page that I can't edit but only manipulate. However, the code does nothing. In chrome console when I print a variable it works fine. The code is below:
//GET val from drop DROP DOWN
var office_id = FieldIDs["OfficeName"];//Gets the input id
var offices;//gets the value from the drop down
$("#FIELD_"+office_id).change(function(){
offices = $(this).val();
}).change();
//The below gets the id's of all the input fields
var address_id = FieldIDs["Address"];
var address2_id = FieldIDs["Address2"];
var city_id = FieldIDs["City"];
var state_id = FieldIDs["State"];
var zip_id = FieldIDs["Zip"];
var phone_4id = FieldIDs["Number4"];//phone
var phone_id = FieldIDs["Number1"];//fax
var pdfm4 = FieldIDs["pdfm4"];
var pdfm = FieldIDs["pdfm"];
if(offices == "SoCal Accounting"){
$('#FIELD_'+address_id).val("7421 Orangewood Avenue");
$('#FIELD_'+address2_id).val("");
$('#FIELD_'+city_id).val("Garden Grove");
$('#FIELD_'+state_id).val("CA");
$('#FIELD_'+zip_id).val("92841");
$('#FIELD_'+phone_4id).val("+1 714.901.5800");//phone
$('#FIELD_'+phone_id).val("+1 714.901.5811");//fax
}
I need to make a calculation in an asp.net page with the value from a usercontrol label.
the user control label is:
<asp:Label ID="LblInvoicePriceValue" runat="server" ></asp:Label>
I include it like this:
<Controls:VehicleInformation ID="VehicleInformationControl" runat="server" />
And my jquery function is something like:
Please see point 1 and 2.
<script type="text/javascript">
$(document).ready(function () {
alert('call function to do calculation here');
// 1. Find in the vehicle information user control the invoiced ammount label
// 2. Find the vat excluded value **after** it was typed in the textbox
// 3. If invoiced ammount is greater than zero, then
// 3.a Find Label Percentage
// 3.b Label.Text = (AmmountWithoutVat/InvoicedAmmount)*100 + '%'
});
</script>
HTML generated:UPdate1
For the label:
<span id="MainContent_VehicleInformationControl_LblInvoicePriceValue" class="bold"></span>
For the textbox:
<input name="ctl00$MainContent$TxtVatExcluded" type="text" id="TxtVatExcluded" class="calculation" />
Update 2:
<script type="text/javascript">
$(document).ready(function () {
alert('call function to do calculation here');
$("#TxtVatExcluded").keypress(function() {
var invoiceprice = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var vatexcluced = $("#TxtVatExcluded").val();
var lblPercentage = $("#MainContent_LblPercentage");
if (invoiceprice > 0) {
lblPercentage.text((vatexcluced / invoiceprice) * 100);
}
})
// 1. Find in the vehicle information user control the invoiced ammount label
// 2. Find the vat excluded value after it was typed in the textbox
// 3. If invoiced ammount is greater than zero, then
// 3.a Find Label Percentage
// 3.b Label.Text = (AmmountWithoutVat/InvoicedAmmount)*100 + '%'
});
</script>
var label_text = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
$("#TxtVatExcluded").val(label_text);
UPDATE
If you want to check if the textfield is blank then only do copy the label then use following code
var label_text = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var txt = $("#TxtVatExcluded").val();
if(txt.length==0)
{
$("#TxtVatExcluded").val(label_text);
}
You can use the rendered ID of the elements to get the values using jQuery
var lbl = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var tbox = $("#TxtVatExcluded").val();
Later when the calculation is complet, you can update the label text as
$("#MainContent_VehicleInformationControl_LblInvoicePriceValue").html("new label");
Update:
To use the logic, where the user types, you have to bind the function to keypress/keyup/keydown event
$("#myinputbox").keypress(function() {
var lbl = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var tbox = $("#TxtVatExcluded").val();
//... so on
}
Update 2:
Since, you are attempting to calculate with the values, it is safer to make sure, there are numbers in the first place. For that, you can use parseInt(), parseFloat() as needed.
$("#TxtVatExcluded").keypress(function() {
var invoiceprice = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var vatexcluced = $("#TxtVatExcluded").val();
var lblPercentage = $("#MainContent_LblPercentage");
if (invoiceprice > 0) {
lblPercentage.text((parseInt(vatexcluced) / parseInt(invoiceprice)) * 100);
}
})
This will get you the value of the label control:
function Calculate()
{
var InvoicedAmmount = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var AmmountWithoutVat = $("#TxtVatExcluded").val();
var Result = (AmmountWithoutVat/InvoicedAmmount)*100
$("#OutputLabel").html(Result + " %");
}
You can attach and onBlur event to your text box to fire your calculation when they leave the text box - you wouldn't really want to re-calculate the amount as they typed.
$(document).ready(function ()
{
$("#TxtVatExcluded").bind("blur",function(){ Calculate(); });
}
I've an html page which has many dynamically created input boxes. The number of text boxes vary each time.
I want to calculate the sum of the numbers the user has entered, and disply it. When the user delete one number the sum should auto calculate.
How can i do it with javascript?
Thanks
In jQuery something like this should work with a few assumptions:
$('.toAdd').live('change', function() {
var total = 0;
$('.toAdd').each(function () {
total += $(this).val();
});
$('#total').val(total);
});
The assumptions being that your input fields all have the class 'toAdd' and that your final input field has an ID of 'total'.
In pure JS:
var elems = document.getElementsByClassName('toAdd');
var myLength = elems.length,
total = 0;
for (var i = 0; i < myLength; ++i) {
total += elems[i].value;
}
document.getElementById('total').value = total;
Let me elaborate when I review my notes but here is a high level answer that I believe will work... (My Java Script is very rusty)...
Make the input boxes share an attribute (or use tag) so you can get a collection to walk through no matter the size... Then on the onkeyup event on every input call this function that will sum the totals. Put the result into another entry with the ID you know beforehand...
You will have to validate input because if one of them is not a number then the total will also be "NAN"
Okay here is a complete working example you can build off of that I just threw together: It obviously needs a great deal of polishing on your end...
<html>
<head>
<script language="javascript">
function AddInputs()
{
var total = 0;
var coll = document.getElementsByTagName("input")
for ( var i = 0; i<coll.length; i++)
{
var ele = coll[i];
total += parseInt(ele.value);
}
var Display = document.getElementById("Display");
Display.innerHTML = total;
}
</script>
</head>
<body>
<input onkeyup="AddInputs()" />
<input onkeyup="AddInputs()" />
<input onkeyup="AddInputs()" />
<span id="Display"></span>
</body>
</html>