I'm creating a website as a small store for personal use, my main question here is how would I code a function for the additon of all of it?
six single check boxes for various types of peripheral devices including printer, monitors, modems or other devices with which you are familiar. Assume the basic computer system price of $500.00 and then add appropriate prices based on user checks.
Monitor 299.99
Printer 129.99
Speakers 49.99
CDRW 159.99
Scanner 129.99
Modem 49.99
If I add just a scanner, my total will be $629.99.
If I add a modem and a monitor, my total will be $849.98.
Here is my current progress, I have not added too much JS code yet as I'm unsure of how I would add this function:
<html>
<head>
<title>Problem 9</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
// Program name: Problem 9
// Purpose: Program 9
// Author: Opack
// Date last modified: 2-13-12
$(function() {
function calculateCost() {
var ret = 500;
var $selected = $('input:checked', $peripherals);
$selected.each(function() {
ret += parseFloat($(this).attr('alt'));
});
return ret.toFixed(2);
}
function setCost() {
$total.text(calculateCost());
}
var $peripherals = $('#peripherals');
var $total = $('#total');
$('input[type="checkbox"]', $peripherals).on('change', setCost);
setCost();
});
</script>
<style>
h1 {
font-size: large;
}
</style>
</head>
<body bgcolor="yellow">
<h1>What peripherals do you want to add?</h1>
<form id="peripherals">
<input type="checkbox" name="Monitor" value="Monitor" alt="299.99">Monitor<br>
<input type="checkbox" name="Printer" value="Printer" alt="129.99">Printer<br>
<input type="checkbox" name="Speakers" value="Speakers" alt="49.99">Speakers<br>
<input type="checkbox" name="CDRW" value="CDRW" alt="159.99">CDRW<br>
<input type="checkbox" name="Scanner" value="Scanner" alt="129.99">Scanner<br>
<input type="checkbox" name="Modem" value="Modem" alt="49.99">Modem<br>
<label for="Cost">Total</label><input type="text" name="Cost" />
</form>
</body>
</body>
</html>
Is this homework?
function calculation(a,b)
{
return a + b;
}
SOURCE
W3Schools: Javascript Operators
W3Schools: Javascript Functions
Here's my attempt. I ended up using jQuery and updating the cost automatically. I attached the cost information to "alt" attribute of the checkboxes. It's possible to do this in some other ways as well. Tweak that to suit your purposes.
jQuery code in case jsbin goes bust...
$(function() {
function calculateCost() {
var ret = 500;
var $selected = $('input:checked', $peripherals);
$selected.each(function() {
ret += parseFloat($(this).attr('alt'));
});
return ret.toFixed(2);
}
function setCost() {
$total.attr('value', calculateCost());
}
var $peripherals = $('#peripherals');
var $total = $('input[name="Cost"]');
$('input[type="checkbox"]', $peripherals).on('change', setCost);
setCost();
});
And relevant HTML:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<meta charset=utf-8 />
<title>Cost Demo/title>
<style>
h1 {
font-size: large;
}
</style>
</head>
<body>
<h1>What peripherals do you want to add?</h1>
<form id="peripherals">
<input type="checkbox" name="Monitor" value="Monitor" alt="299.99">Monitor<br>
<input type="checkbox" name="Printer" value="Printer" alt="129.99">Printer<br>
<input type="checkbox" name="Speakers" value="Speakers" alt="49.99">Speakers<br>
<input type="checkbox" name="CDRW" value="CDRW" alt="159.99">CDRW<br>
<input type="checkbox" name="Scanner" value="Scanner" alt="129.99">Scanner<br>
<input type="checkbox" name="Modem" value="Modem" alt="49.99">Modem<br>
<label for="Cost">Total</label><input type="text" name="Cost" />
</form>
</body>
</html>
Related
I have a button and I would like to replace it with other HTML object loaded by google app script via method HtmlService.createTemplateFromFile('HTML_file').
The button onclick function is written in javascript in .html file:
<div id="add_form_button_wraper">
<input type="button" id="add_form" onclick="addForm()" value="Add Form">
</div>
<script>
function addForm() {
innerHTML = google.script.run.getForm(some_args);
document.getElementById("add_form_button_wraper").innerHTML =
innerHTML;
}
</script>
The Code.gs code looks following:
getForm(arg1, arg2) {
// Creating HTML template from html file.
var template = HtmlService.createTemplateFromFile(HTML_TEMPLATE);
template.arg1 = arg1;
template.arg2 = arg2;
return template.evaluate().getContent();
}
After clicking the button the content of the div is changed to undefined. I tried also HTMLService.createTemplateFromFile().getCode() with the same effect.
How to insert into div the raw html code obtained from app script HTMLService?
A Simple Web App Example
Here's how I do my dialogs and web apps. I know it doesn't necessarily pertain to your particular situation but hopefully a working example can give you some ideas as to how you can proceed.
This is a simple example of a standard web app form. You can view it as a dialog or run it as a webapp. It stores all of the response on a sheet.
Code.gs:
function onOpen()
{
SpreadsheetApp.getUi().createMenu('My Tools')
.addItem('Display Dialog', 'displayDialog')
.addToUi();
}
function doGet()
{
var output=HtmlService.createHtmlOutputFromFile('CyclingSurvey');
return output.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
Cycling Survey.gs:
function storeCyclingSurveyResults(rA)
{
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('CyclingSurvey');
var ts=Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "MM/dd/yyyy HH:mm:ss");
rA.splice(0,0,ts);
sh.appendRow(rA);
return true;
}
function displayDialog()
{
var html=HtmlService.createHtmlOutputFromFile('CyclingSurvey').setWidth(800).setHeight(500);
SpreadsheetApp.getUi().showModelessDialog(html, 'Cycling Survey');
}
Cycling Survey.html:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function recordData()
{
var q1=$('#q1').val();
var q2=$('input[name="prefer"]:checked').val();
var checked = [];
$("input[name='own']:checked").each(function (){checked.push($(this).val());});
var q3=checked.join(', ');
var q4=$('#q4').val();
var rA=[];
rA.push(q1);
rA.push(q2);
rA.push(q3);
rA.push(q4);
google.script.run
.withSuccessHandler(setResponse)
.storeCyclingSurveyResults(rA);
}
function setResponse()
{
$('#reply').css('display','inline');
$('#collect').css('display','none');
}
console.log('script here');
</script>
<style>
#reply{display:none;}
#collect{display:block;}
</style>
</head>
<body>
<div id="reply" >Thanks for taking the time to take our survey. Your results have been recorded.</div>
<div id="collect">
<div style="font-weight:bold">What do you like about cycling?</div>
<textarea id="q1" rows="4" cols="50" placeholder="Enter Text Here..."></textarea>
<div style="font-weight:bold">Which type of bike do you prefer?</div>
<input type="radio" name="prefer" value="mountain bike">Mountain Bike<br />
<input type="radio" name="prefer" value="road bike" checked>Road Bike<br />
<input type="radio" name="prefer" value="fitness bike">Fitness Bike<br />
<div style="font-weight:bold">What types of bikes do you currently own?</div>
<input type="checkbox" name="own" value="Mountain Bike">Mountain Bike<br />
<input type="checkbox" name="own" value="Road Bike" checked>Road Bike<br />
<input type="checkbox" name="own" value="All Terrain Bike">All Terain Bike<br />
<input type="checkbox" name="own" value="Fitness Bike">Fitness Bike<br />
<div style="font-weight:bold">Do you prefer riding with others or alone?</div>
Alone<input id="q4" type="range" name="rating" max="10" min="0" step="1" defaultValue="5"/>Others<br />
<input type="button" id="btn1" value="Submit" onClick="recordData();" />
</div>
</body>
</html>
Good afternoon,
I am trying to tick a checkbox in my html page using a script.
Unfortunately, I get the following error message :
SCRIPT5007: Unable to set property 'checked' of undefined or null reference
File: ajax3, Line: 37, Column: 5
Do you have an idea what went wrong in my code?
Thanks a lot and have a great Sunday.
Laurent
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Demo for Ajax Auto Refresh</title>
<link rel="stylesheet" type="text/css" href="css/mystyle_day.css" />
<script src="jquery-2.1.3.min.js"></script>
<script>
/* AJAX request to checker */
function check(){
$.ajax({
type: 'POST',
url: 'checker.php',
dataType: 'json',
data: {
counter:$('#message-list').data('counter')
}
}).done(function( response ) {
/* update counter */
$('#message-list').data('counter',response.current);
/* check if with response we got a new update */
if(response.update==true){
$('#message-list').html(response.news);
sayHello();
}
});
}
//Every 1 sec check if there is new update
setInterval(check,1000);
</script>
<script>
function sayHello(){
//console.log("Coucou");
check();
}
function check() {
document.getElementById("chk1").checked = true;
}
function uncheck() {
document.getElementById("chk1").checked = false;
}
</script>
</head>
<body>
<div id="message-list" data-counter="<?php echo (int)$db->check_changes();?>">
</div>
<input type="checkbox" name="chk1" id="chk1"> Living room<br>
<input type="checkbox" name="chk2" id="chk2"> Entrance<br>
<input type="checkbox" name="chk3" id="chk3"> Kitchen<br>
</body>
</html>
As suggested by nmnsud and gcampbell, I have replaced value="chk1" by id="chk1". The correct bit of code is now the following :
<input type="checkbox" name="chk1" id="chk1"> Living room<br>
<input type="checkbox" name="chk2" id="chk2"> Entrance<br>
<input type="checkbox" name="chk3" id="chk3"> Kitchen<br>
Thanks a lot for your contribution. Best wishes,
Laurent
Is it possible to get a dozen results from this single basic calculation? I have two output textboxes in the sample code; how can I get these two fields to work?
<!DOCTYPE html>
<html lang = "en">
<head>
<title> multiple results calculation </title>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<link rel="style" href="css/main.css" type"text/css"/>
<!-- I need multiple results from single calculation!
<script type="text/javascript">
function sum()
{
var width = document.multiple results.width.value;
var height = document.multiple results.value;
var sum = parseInt(width) * parseInt(height) /144;
document.getElementById('Calculate').value = sum;
document.getElementById("results1").readOnly=true;
document.getElementById("results2").readOnly=true;
var result1= $1.99;
var result2= $2.99;
document.getElementById('Calculate').value = sum * result1;
document.getElementById('Calculate').value = sum * result2;
}
</script>
-->
</head>
<body>
<div>
<H2> Multiple instant results from single calculation</h2>
<p> the goal eventually is to have about a dozen results from this single calculation
</div>
<form name="multiple results">
<label for="width"> Width: </label>
<input type="number" <id="width" maxlength="4" size="10" value=""/>
<label for="height"> Height: </label>
<input type="number" <id="height" maxlength="4" size="10" value=""/>
<input type="button" name="button" value="Calculate" onClick="sum"/>
<div>
<label for="result1"> Result1: $ </label>
<input type="number" id="result1" name="result1"/>
<label for="result2"> Result2: $ </label>
<input type="number" id="result2" name="result2"/>
</div>
</form>
</body>
</html>
I found a solution by removing the first document.getElementById('Calculate').value = sum;, changed the remaining getElementById's and input type's to result and result2 also added the missing value="" to input, not necessary but renaming Id's helped me
I have 3 text boxes (testbox, testbox2, testbox3) that get values from an input field, radio button selection and checkbox/tick. The correct values go into testbox, testbox2, testbox3.
However, I need the total of testbox, testbox2, testbox3 to go into text box 'total' - with the total to change if the users selects different radio buttons or tick/unticks etc..
One more thing I need the total to also be shown in the form, echo, (in addition to going into the text box - which will eventually be hidden).
Thank you.
<head>
<script type="text/javascript">
function checkboxClick() {
var textbox = document.forms[0].testbox3;
textbox.value = (textbox.value == 0) ? '1.00' : '0.00';
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<form action="" method="get">
<input name="form1" type="radio" onclick="document.forms[0].testbox2.value='0.00'; "/>
<input name="form1" type="radio" onclick="document.forms[0].testbox2.value='1.00'; "/>
<input name="" type="checkbox" value="" onclick='checkboxClick()'/>
<input name="testbox" type="text" value"2.00"/>
<input name="testbox2" type="text" value"0.00"/>
<input name="testbox3" type="text" value="0.00"/>
<input name="total" type="text" value=""/>
</form>
<body>
</body>
</html>
How about writing a function to update the total (and being careful to parse the textbox inputs as floats):
function updateTotal() {
var textbox1val = parseFloat(document.forms[0].testbox.value);
var textbox2val = parseFloat(document.forms[0].testbox2.value);
var textbox3val = parseFloat(document.forms[0].testbox3.value);
var total = textbox1val + textbox2val + textbox3val;
document.forms[0].total.value = total;
}
And then calling this function in an onchange attribute?
I am trying to create a form with many groups containing many radio buttons. When the user selects a button, I would like to calculate the sum of each selected radio button value and show this sum to the user.
I have found a plugin for jQuery which will do the calculation, this plugin use the name attribute of the buttons to calculate. For example, it will sum the values of all buttons which have the name sum.
So far, I have tried two ways of setting this up: in the first method, I create a hidden field for each group to hold the sum of the selected values inside it, this hidden field gets the value but the problem is that the total value will not update when a user selects a button. My code looks like this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script src="jquery.js" type="text/javascript">
</script>
<script src="calc.js" type="text/javascript">
</script>
<script src="calc_f.js" type="text/javascript">
</script>
<script type="text/javascript">
function DisplayPrice(price){
$('#spn_Price').val(price);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<input type="hidden" id="spn_Price" name="sum" value="">
<br>
<input id="rdo_1" type="radio" value="159" name="price" onclick="DisplayPrice(this.value);">
<br>
<input id="rdo_2" type="radio" value="259" name="price" onclick="DisplayPrice(this.value);">
<br>
<input type="text" name="totalSum" id="totalSum" value="" size="2" readonly="readonly">
</form>
</body>
</html>
In this code, the input tag with the name totalSum is where the value will update, but it won't update when changing the buttons.
As I said before, the reason why I use a hidden field is to hold each group's subtotal. It has the name sum, which indicates to the plugin that it should be added to others.
I dont know if this is the right way to do this, i have tried to change the name attribute of the buttons when user click them to sum but that didn`t work either!
Here is plugin address : http://www.pengoworks.com/workshop/jquery/calculation/calculation.plugin.htm
How can I do this ?
Plugin schmugin. Get rid of your onclick and try this:
$("input[type=radio]").click(function() {
var total = 0;
$("input[type=radio]:checked").each(function() {
total += parseFloat($(this).val());
});
$("#totalSum").val(total);
});
Untitled Document
<script type="text/javascript">
function DisplayPrice(price){
var val1 = 0;
for( i = 0; i < document.form1.price.length; i++ ){
if( document.form1.price[i].checked == true ){
val1 = document.form1.price[i].value;
}
}
var val2 = 0;
for( i = 0; i < document.form2.price2.length; i++ ){
if( document.form2.price2[i].checked == true ){
val2 = document.form2.price2[i].value;
}
}
var sum=parseInt(val1) + parseInt(val2);
document.getElementById('totalSum').value=sum;
}
</script>
</head>
<body>
Choose a number:<br>
<form name="form1" id="form1" runat="server">
<br>
<input id="rdo_1" type="radio" value="159" name="price" onclick="DisplayPrice(this.value);">159
<br>
<input id="rdo_2" type="radio" value="259" name="price" onclick="DisplayPrice(this.value);">259
<br>
</form>
Choose another number:<br>
<form name="form2" id="form2" runat="server">
<br>
<input id="rdo_1" type="radio" value="345" name="price2" onclick="DisplayPrice(this.value);">345
<br>
<input id="rdo_2" type="radio" value="87" name="price2" onclick="DisplayPrice(this.value);">87
<br>
</form>
<input type="text" name="totalSum" id="totalSum" value="" size="2" readonly="readonly">
</body>
The code above will dinamically sum the checked values from both groups.
parseInt will convert to integers. Use parseFloat otherwise.