Some of the methods are working but not all of them - javascript

I am new to Js and I am having trouble with the code. The problem is that when I multiply different methods together the program does not work. However, some of the methods are are working even though they are kind of identical. The other problem is that I have to change the first selection first and then the other to get the total I need. I want to get a total that changes whenever I choose any selection from the drop box regardless of ordering. I know I am foreseeing a mistake here or simply cant understand. Please feel free to point out my mistakes and help me better my code because I know its more complicated than it should be. Thank you for your help.
HTML
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="js/scriptt.js "></script>
</head>
<body onload="hideTotal()">
<form method="POST" class="device"/>
<center class="all" >
<div class= "data">
<label class="req">Select The Device</label>
<select class="mydevice" id= "selectDevice" onChange="calculateTotal()">
<option> None </option>
<option value="100" id='lg'> LG X CHARGE </option>
<option value="129"> ZTE MAX XL </option>
<option value="123"> LG DYNASTY </option>
<option value="400"> LG TRIBUTE </option>
</select>
<label for="For" class="req"> For </label>
<select class="mydevice" id="port" onChange="calculateTotal()">
<option id= 'none' value='none'> None </option>
<option id='port' value="129" >Port-In</option>
<option class="upgrade">Upgrade</option>
<option class="newAct">New Activation</option>
</select>
<label for="Plan" class="req">Plan</label>
<select class="plan" id='plan' onChange="calculatedToral()">
<option>None</option>
<option value="35" >$35 plan</option>
<option value="50">$50 plan</option>
<option value="60">$60 plan</option>
</select>
<div class="access" >
<label for="phoneInsurance"> Phone Insurance </label>
<select class="myinsurance" id='insurance' onChange="calculatedToral()">
<option>None</option>
<option value="7">Yes</option>
</select>
<label for="phoneCase"> Phone Case </label>
<select class="mycases" id='case' onChange="calculatedToral()">
<option>None</option>
<option value="25">Regular</option>
<option value="35">Wallet</option>
</select>
<label for="screenProtector"> Screen Protector </label>
<select class="myscreen" id='screen' onChange="calculatedToral()">
<option value="15">Yes</option>
<option>No</option>
</select>
<center>
<div id="total"></div>
Js
var device_prices = new Array();
device_prices["100"]=100;
device_prices["129"]=129;
device_prices["123"]=123;
device_prices["400"]=400;
var port_prices = new Array();
port_prices["129"]=0.097;
var plan_prices = new Array();
plan_prices["35"]=35;
plan_prices["50"]=50;
plan_prices["60"]=60;
var insurance_prices = new Array();
inusrance_prices["7"]=7;
var phone_case = new Array();
phone_case["25"] = 25;
phone_case["30"] = 30;
var screen_protector = new Array();
screen_protector["15"] = 15;
function getDevicePrice() {
var deviceSelect = document.getElementById('selectDevice');
//alert(device_prices[deviceSelect.value]);
return device_prices[deviceSelect.value];
}
function getPortPrice() {
var portSelect = document.getElementById('port');
return port_prices[portSelect.value];
}
function getPlanPrice() {
var planSelected = document.getElementById('plan');
return plan_prices[planSelected.value];
}
function getInsurancePrice() {
var insurancee = document.getElementById('insurance');
return insurance_prices[insurancee.value];
}
function getCasePrice() {
var caseSelect = document.getElementById('case');
return phone_case[caseSelect.value];
}
function getScreenPrice() {
var screenSelect = document.getElementById('screen');
return screen_protector[screenSelect.value];
}
function calculateTotal() {
var total = getDevicePrice()*getPlanPrice()*getPortPrice();
total = total.toFixed(2);
var totalEl = document.getElementById('total');
document.getElementById('total').innerHTML = "Your Total is: $" + total;
totalEl.style.display = 'block';
}
function hideTotal() {
var totalEl = document.getElementById('total');
totalEl.style.display = 'none';
}

spelling
var insurance_prices = new Array();
inusrance_prices["7"]=7;
funtion or method not define
calculatedToral
var device_prices = new Array();
device_prices["100"]=100;
device_prices["129"]=129;
device_prices["123"]=123;
device_prices["400"]=400;
var port_prices = new Array();
port_prices["129"]=0.097;
var plan_prices = new Array();
plan_prices["35"]=35;
plan_prices["50"]=50;
plan_prices["60"]=60;
var insurance_prices = new Array();
insurance_prices["7"]=7;
var phone_case = new Array();
phone_case["25"] = 25;
phone_case["30"] = 30;
var screen_protector = new Array();
screen_protector["15"] = 15;
function getDevicePrice() {
var deviceSelect = document.getElementById('selectDevice');
//alert(device_prices[deviceSelect.value]);
alert("1");
return device_prices[deviceSelect.value];
}
function getPortPrice() {
var portSelect = document.getElementById('port');
alert("2")
return port_prices[portSelect.value];
}
function getPlanPrice() {
var planSelected = document.getElementById('plan');
alert("3")
return plan_prices[planSelected.value];
}
function getInsurancePrice() {
alert("4")
var insurancee = document.getElementById('insurance');
return insurance_prices[insurancee.value];
}
function getCasePrice() {
alert("5")
var caseSelect = document.getElementById('case');
return phone_case[caseSelect.value];
}
function getScreenPrice() {
alert("6")
var screenSelect = document.getElementById('screen');
return screen_protector[screenSelect.value];
}
function calculateTotal() {
alert("7")
var total = getDevicePrice()*getPlanPrice()*getPortPrice();
total = total.toFixed(2);
var totalEl = document.getElementById('total');
document.getElementById('total').innerHTML = "Your Total is: $" + total;
totalEl.style.display = 'block';
}
function calculatedToral()
{
alert("8")
}
function hideTotal() {
alert("9")
var totalEl = document.getElementById('total');
totalEl.style.display = 'none';
}
i was corrected your all function or method of your JavaScript and all are working (i was add alert() for function check). check calculation errors yourself

The JS calls in your HTML tags have wrong names.
Eg: You've calculatedToral() instead of calculatedTotal()in the following:
<select class="myinsurance" id='insurance' onChange="calculatedToral()">
<option>None</option>
<option value="7">Yes</option>
</select>
Check all the names properly.
Also, some footnotes since you're a beginner:
Try to avoid inline scripting. (look at this) I.e., as far as possible, don't mix the javascript event calls (like onChange(), onClick()) in the HTML tags. It'll make the code difficult to read and change in future.
Instead of inline scripting, try to put all Javascript either within the <script> tags (at end of page is usually better). Use .getElementsByClass() for wider control and .getElementById() for granular control of events.
Also, since you're using jQuery, include the <script> calling the jQuery CDN at the end, just before </body>

Related

Google Sheets Script Editor HTML User Interface not able to read return type

I am attempting to take a custom array from the script editor and return it to my HTML UI in order to create a customized drop down menu search bar.
The first major problem I am encountering is that I am unable to assign a variable to a value from a function's return type. Below is the code I have written:
CODE:
function showSidebar() {
var html = HtmlService.createHtmlOutputFromFile('Search5')
.setTitle('My custom sidebar')
.setWidth(300);
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.showSidebar(html);
}
function called(value){
Logger.log("CALLED");
Logger.log(value);
var html= HtmlService.createHtmlOutputFromFile('Search5').setTitle("NEW sidebar");
SpreadsheetApp.getUi().showSidebar(html);
}
function getArray(){
Logger.log("get array called");
var array = ["test","a", "b", "c"];
return array;
}
function counter(i){
Logger.log(i);
}
HTML:
<!DOCTYPE html>
<html>
<head>
<title>HTML form Tag</title>
</head>
<body>
<form action="" method = "get">
<select name="cars" id = "test">
<div id="wrapper"></div>
<option value="volvo">Volvo XC90</option>
<option value="saab">Saab 95</option>
<option value="mercedes">Mercedes SLK</option>
<option value="audi">Audi TT</option>
<option value="select">SELECTED</option>
<option value="audi">Audi TT</option>
</select>
<input type="submit" name = "submitButton" onclick = "get()" value="Submit">
</form>
<script>
var array[];
function get(){
var e = document.getElementById("test");
var strUser = e.options[e.selectedIndex].value;
google.script.run.called(strUser);
}
function read(){
array = google.script.run.getArray();
google.script.run.counter(9); //debugging purposes
}
function test(){
google.script.run.counter();
}
function addHtml(){
read();
google.script.run.counter(array[3]); //debugging purpoes
var text = "";
for (i = 0; i < array.length; i++) {
text += '<option value="' + i+ '">'+ i+ '</option>\n';
google.script.run.counter(text); //debugging purposes
}
document.getElementById("wrapper").innerHTML = text;
}
window.onload = function () {
addHtml();
}
</script>
</body>
</html>
The line of code
document.getElementById("wrapper").innerHTML = text;
is intended to customize the drop down menu options. However, that doesn't seem to be working as well despite extensive research.
Back to the original question, why is my HTML code unable to assign the return type from my script to the javascript variable within my HTML file?
Thanks.
You want to use the values from getArray() of Google Apps Script at Javascript.
If my understanding is correct, how about this modification?
Modification points:
Modify from var array[]; to var array = [];.
Move <div id="wrapper"></div> to outside of select.
In your current script, I think that an error occurs.
google.script.run doesn't return values. When you want to use the returned values from Google Apps Script side, please use withSuccessHandler().
google.script.run works with the asynchronous process.
In your script, when addHtml() is run, google.script.run.counter(array[3]) and the for loop is run before read() is finished. By this, the undefined array is used.
When above points are reflected to your script, it becomes as follows.
Modified script:
In this modification, your Javascript was modified.
<!DOCTYPE html>
<html>
<head>
<title>HTML form Tag</title>
</head>
<body>
<form action="" method = "get">
<div id="wrapper"></div> <!-- Modified -->
<select name="cars" id = "test">
<option value="volvo">Volvo XC90</option>
<option value="saab">Saab 95</option>
<option value="mercedes">Mercedes SLK</option>
<option value="audi">Audi TT</option>
<option value="select">SELECTED</option>
<option value="audi">Audi TT</option>
</select>
<input type="submit" name = "submitButton" onclick = "get()" value="Submit">
</form>
<script>
var array = []; // Modified
function get(){
var e = document.getElementById("test");
var strUser = e.options[e.selectedIndex].value;
google.script.run.called(strUser);
}
function test(){
google.script.run.counter();
}
function read() { // Modified
google.script.run.withSuccessHandler(addHtml).getArray();
}
function addHtml(e){ // Modified
array = e;
var text = "";
for (i = 0; i < array.length; i++) {
text += '<option value="' + i+ '">'+ i+ '</option>\n';
}
document.getElementById("wrapper").innerHTML = text;
}
window.onload = function() {
read(); // Modified
}
</script>
</body>
</html>
References:
Class google.script.run
withSuccessHandler(function)

Javascript won't read from "select" in a form

I am trying to get my code to read a value based off the selected item from a select list in my form, but it says it's undefined. When I simply give the function a value and tell it to return the value, it reads, but won't take values from the form.
The following is the code I'm using
for the form (in html):
<form action="" id="orderForm" name="orderForm" onsubmit="return false;">
<select id="item" name='item' onchange="calculateCost()">
<option value="None">Select Item</option>
<option value="Candlestick">Candlestick ($10)</option>
<option value="Bowl">Bowl ($10)</option>
<option value="Burl_Bowl">Burl Bowl ($20)</option>
<option value="Clock">Clock ($15)</option>
<option value="Vase">Vase ($5)</option>
<option value="Pen">Pen ($2)</option>
<option value="Top">Spinning Top ($1)</option>
</select>
<div id="totalPrice">hallo</div>
</form>
and the javascript reads
function calculateCost()
{
var orderPrice = getItemPrice();
document.getElementById('totalPrice').innerHTML = orderPrice;
}
var item_prices= new Array();
item_prices["None"]=0;
item_prices["Candlestick"]=10;
item_prices["Bowl"]=10;
item_prices["Burl_Bowl"]=20;
item_prices["Clock"]=15;
item_prices["Vase"]=5;
item_prices["Pen"]=2;
item_prices["Top"]=1;
function getItemPrice()
{
var itemPrice = 0;
var theForm = document.forms["orderForm"];
var selectedItem = theForm.elements["item"];
itemPrice = item_prices[selectedItem.value];
return itemPrice;
}
HTMLCollection.item() is method of HTML select element Returns the specific node at the given zero-based index into the list. Returns null if the index is out of range.
theForm.elements["item"] will return function expression of the HTMLCollection.item and which is causing the undefined value as theForm.elements["item"] does not have property value
Either pass this in inline-event or use other id and name attribute to select element than item
function calculateCost(elem) {
var orderPrice = getItemPrice(elem.value);
document.getElementById('totalPrice').innerHTML = orderPrice;
}
var item_prices = [];
item_prices["None"] = 0;
item_prices["Candlestick"] = 10;
item_prices["Bowl"] = 10;
item_prices["Burl_Bowl"] = 20;
item_prices["Clock"] = 15;
item_prices["Vase"] = 5;
item_prices["Pen"] = 2;
item_prices["Top"] = 1;
function getItemPrice(val) {
var itemPrice = 0;
itemPrice = item_prices[val];
return itemPrice;
}
<form action="" id="orderForm" name="orderForm" onsubmit="return false;">
<select id="item" name='item' onchange="calculateCost(this)">
<option value="None">Select Item</option>
<option value="Candlestick">Candlestick ($10)</option>
<option value="Bowl">Bowl ($10)</option>
<option value="Burl_Bowl">Burl Bowl ($20)</option>
<option value="Clock">Clock ($15)</option>
<option value="Vase">Vase ($5)</option>
<option value="Pen">Pen ($2)</option>
<option value="Top">Spinning Top ($1)</option>
</select>
<div id="totalPrice">hallo</div>
</form>
Edit: Or just use getElementById => var selectedItem = document.getElementById('item'); to access the select element.Fiddle here
This entire operation could be simplified a bit as well.
var item_prices= new Array();
item_prices["None"]=0;
item_prices["Candlestick"]=10;
item_prices["Bowl"]=10;
item_prices["Burl_Bowl"]=20;
item_prices["Clock"]=15;
item_prices["Vase"]=5;
item_prices["Pen"]=2;
item_prices["Top"]=1;
EDIT, you should use an object here if you want to be correct.
item_prices = {
None: 0,
Candlestick: 10
};
// etc...
document.getElementById('item').addEventListener('change', function (event) {
document.getElementById('totalPrice').innerHTML = item_prices[event.target.value];
});

JavaScript NaN Error

I'm making website that includes running total. By that I mean as the user selects items on a drop-down menu, a running cost will increase/decrease accordingly. Similar (if not the same) as this.
The issue I'm having is that when the user starts selecting items, "Total Price For the Build £NaN" appears. I'm new to Javascript so I really have no idea why this is happening.
The HTML:
<form action="" id="partsForm" onsubmit="return false;">
<fieldset>
<legend>Choose your parts</legend>
<label>CPU</label>
<select id="cpu" name="cpu" onchange="calculateTotal()">
<option value="None">None</option>
<option value"A6">AMD A6 Dual Core (£56)</option>
<option value="A8">AMD A8 Quad Core (£72)</option>
<option value="760k">Athlon 760k Quad (£72)</option>
<option value="A10">AMD A10 Quad Core (£119)</option>
</select>
<br /> <br />
<label>Motherboard</label>
<select id="mobo" name="mobo" onchange="calculateTotal()">
<option value="None">None</option>
<option value"DS2">Gigabyte A88X-DS2 (£45)</option>
<option value="D3H">Gigabyte A88X D3H (£60)</option>
<option value="A88X-M">ASUS A88X-M Plus (£67)</option>
<option value="A88X-UP4">Gigabyte A88X-UP4 (£109)</option>
</select>
<br /> <br />
<label>Graphics Chip</label>
<select id="gfx" name="gfx" onchange="calculateTotal()">
<option value="None">None</option>
<option value"260X">AMD R7 260X (£149)</option>
<option value="650ti">GTX 650ti Boost (£169)</option>
<option value="750ti">GTX 750ti (£179))</option>
<option value="R9_270">AMD R9 270 (£205)</option>
</select>
<br /> <br />
<label>Power Supply</label>
<select id="psu" name="psu" onchange="calculateTotal()">
<option value="None">None</option>
<option value"CX430">Corsair CX430 (£49)</option>
<option value="CX500">Corsair CX500 (£59)</option>
<option value="CX600">Corsair CX600 (£69)</option>
<option value="CX750">Corsair CX750 (£89)</option>
</select>
<br /> <br />
<label>Case</label>
<select id="case" name="case" onchange="calculateTotal()">
<option value="None">None</option>
<option value"Fractal">Fractal Core 1000 (£39)</option>
<option value="NZXT">NZXT Source 210 Elite (£59)</option>
<option value="200R">Corsair 200R (£69)</option>
<option value="300R">Corsair 300R (£89)</option>
</select>
<br /> <br />
<label>Memory</label>
<select id="ram" name="ram" onchange="calculateTotal()">
<option value="None">None</option>
<option value"4GB">4GB DDR3 (£39)</option>
<option value="8GB">8GB DDR3 (£69) </option>
<option value="16GB">16GB DDR3 (£109)</option>
</select>
<br /> <br />
<label>Storage</label>
<select id="storage" name="storage" onchange="calculateTotal()">
<option value="None">None</option>
<option value="1TB">1TB HDD (£54)</option>
<option value="120GB_SSD">120GB SSD (£69)</option>
<option value="256GB_SSD">256GB SSD (£119)</option>
<option value="1TB_SSD">1TB + 120GB SSD (£119)</option>
</select>
<div id="totalPrice" style="display:block;"> </div>
</fieldset>
The JavaScript:
//CPU Prices
var cpu_prices = new Array();
cpu_prices["None"]=0;
cpu_prices["A6"]=56;
cpu_prices["A8"]=72;
cpu_prices["760k"]=72;
cpu_prices["A10"]=119;
//MotherBoard Prices
var mobo_prices = new Array();
mobo_prices["None"]=0;
mobo_prices["DS2"]=45;
mobo_prices["D3H"]=60;
mobo_prices["A88X-M"]=67;
mobo_prices["A88X-UP4"]=109;
//Graphics Chip Prices
var gfx_prices = new Array();
gfx_prices["None"]=0;
gfx_prices["260X"]=149;
gfx_prices["650ti"]=169;
gfx_prices["750ti"]=179;
gfx_prices["R9_270"]=205;
//Power Supply Prices
var psu_prices = new Array();
psu_prices["None"]=0;
psu_prices["CX430"]=49;
psu_prices["CX500"]=59;
psu_prices["CX600"]=69;
psu_prices["CX750"]=89;
//Case Prices
var case_prices = new Array();
case_prices["None"]=0;
case_prices["Fractal"]=39;
case_prices["NZXT"]=59;
case_prices["200R"]=69;
case_prices["300R"]=89;
// Memory Prices
var ram_prices = new Array();
ram_prices['None']=0;
ram_prices["4GB"]=39;
ram_prices["8GB"]=69;
ram_prices["16GB"]=109;
//Storage Prices
var storage_prices = new Array();
storage_prices['None']=0;
storage_prices['1TB']=54;
storage_prices['120GB_SSD']=69;
storage_prices['256GB_SSD']=119;
storage_prices['1TB_SSD']=119;
//This will find the price of the CPU chosen by the user
function getCPUPrice() {
var CpuPrice=0
var theForm = document.forms["partsForm"];
var selectedCpu = theForm.elements['cpu'];
//sets CpuPrice to whatever the user has chosen
CpuPrice = cpu_prices[selectedCpu.value];
//return CpuPrice
return CpuPrice;
}
//This will find the price of the Motherboard chosen by the user
function getMOBOPrice() {
var MoboPrice=0
var theForm = document.forms["partsForm"];
var selectedMobo = theForm.elements['mobo'];
//sets MoboPrice to whatever the user has chosen
MoboPrice = mobo_prices[selectedMobo.value];
//return MoboPrice
return MoboPrice;
}
//This will find the price of the Graphics Chip chosen by the user
function getGFXPrice() {
var GfxPrice=0
var theForm = document.forms["partsForm"];
var selectedGfx = theForm.elements['gfx'];
//sets GfxPrice to whatever the user has chosen
GfxPrice = gfx_prices[selectedGfx.value];
//return GfxPrice
return GfxPrice;
}
//This will find the price of the Power Supply chosen by the user
function getPSUPrice() {
var PsuPrice=0
var theForm = document.forms["partsForm"];
var selectedPsu = theForm.elements['psu'];
//sets PsuPrice to whatever the user has chosen
PsuPrice = psu_prices[selectedPsu.value];
//return PsuPrice
return PsuPrice;
}
//This will find the price of the Case chosen by the user
function getCasePrice() {
var CasePrice = 0;
var theForm = document.forms["partsForm"];
var selectedCase = theForm.elements['case'];
//sets CasePrice to whatever the user has chosen
CasePrice = case_prices[selectedCase.value];
//return CasePrice
return CasePrice;
}
//This will find the price of the Memory chosen by the user
function getRamPrice() {
var RamPrice=0
var theForm = document.forms["partsForm"];
var selectedRam = theForm.elements['ram'];
//sets RamPrice to whatever the user has chosen
RamPrice = ram_prices[selectedRam.value];
//return RamPrice
return RamPrice;
}
//This will find the price of the Storage device chosen by the user
function getStoragePrice() {
var StoragePrice=0;
var theForm = document.forms["partsForm"];
var selectedStorage = theForm.elements['storage'];
//sets StoragePrice to whatever the user has chosen
StoragePrice = storage_prices[selectedStorage.value];
//return StoragePrice
return StoragePrice;
}
//Get the Totals
function calculateTotal()
{ //gets prices from other functions
var buildPrice = getCPUPrice() + getMOBOPrice() +
getGFXPrice()+ getPSUPrice() + getCasePrice() + getRamPrice() + getStoragePrice();
//displays total cost
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total Price For the Build £"+buildPrice;
}
function hideTotal()
{
var divobj = document.getElementById('totalPrice');
divobj.style.display='none';
}
I appreciate that it's quite a lot of similar code, but I'd really like to thoroughly understand why this isn't working.
Thanks in advance.
Let me know if there's anything missing from this.
Actually looks like you fell prone to the copy/paste snafu. Each of your 2nd list items, was missing an "=".
Original:
<select id="cpu" name="cpu" onchange="calculateTotal()">
<option value="None">None</option>
<option value"A6">AMD A6 Dual Core (£56)</option>
<option value="A8">AMD A8 Quad Core (£72)</option>
<option value="760k">Athlon 760k Quad (£72)</option>
<option value="A10">AMD A10 Quad Core (£119)</option>
</select>
Fixed Fiddle
You have a typo in your code
<option value"CX430">Corsair CX430 (£49)</option>
There is a = missing after value
And this is the same error for each first item of your lists.
I tried your code with the second choice each time, and it worked.
That's because of the js wrapping :
If you wrap in an onload function, the function calculateTotal() is provate, it can't be accessed anywhere but in the onLoad callback. See http://jsfiddle.net/U2zSk. If you wrap directly in head, it's working. See http://jsfiddle.net/U2zSk/2/
your Variable buildPrice is the result of many different methods that query selectors. If you have not selected a value in all the selectors, the function that calculates the value of the selector will not return a number and when the final sum that will result NaN. If you put in all selector as the default 'None' option should not give you problems.
Additionally you have many options incorrect:
<option value"Fractal">Fractal Core 1000 (£39)</option>
<option value"CX430">Corsair CX430 (£49)</option>
<option value"260X">AMD R7 260X (£149)</option>
<option value"A6">AMD A6 Dual Core (£56)</option>

drop down list with more then one dilimiter. can get JS to work

Ok so i am trying to get a textarea where a user can type in text. select a delimiter from a dropdown list. Hit count and it will count how many times it splits.
I cant seem to get my code to split at all. here is my code.
JavaScript
window.onload = function() {
document.getElementById("change").onclick = function() {
var paragraph = document.getElementById('box').value;
var x = document.getElementById("changeCase");
var getInfo = document.getElementById('ParaWrite');
var LowerCase = " ";
var splitAT = " ";
alert("above the for loop");
if (x.checked === true)
{
LowerCase = paragraph.toLowerCase();
}
else
{
LowerCase = paragraph;
}
for (var i = 0; i <document.form1.split.options.length; i++)
{
if (document.form1.split.options[i].selected === true)
{
splitAT = paragraph.split(options[i]);
}
}
document.write(splitAT);
doc write is just so i can see if it even makes it that far in the code and it does not.
here is my HTML
<form name="form1" id="form1">
<textarea type="text" id="box" value=""/></textarea>
<input type='checkbox' name='write' id='changeCase' value='Check'/><br>
<input type='button' value="Count" id="change"/>
<select name="split" id="split">
<option value="like">like</option>
<option value="monkey">monkey</option>
<option value="I">I</option>
<option value=".">.</option>
<option value=",">,</option>
<option value="?">?</option>
<option value=" ">[Space]</option>
</select>
</form>
<div id="ParaWrite">
</div>
options is not defined.
splitAT = paragraph.split(document.form1.split.options[i]);
http://jsfiddle.net/ExplosionPIlls/KeZEd/

jQuery to calculate live output based on form entries

I have a form. The user will fill it out, and at the bottom of that form I am trying to display a value based values inserted into the form page.
I'm so far not getting any kind of output at all, here is my attempt:
HTML FORM:
<form id="myform">
<select
name="sv_313"
onchange="calculate()"
id="sv_313"
>
<option value="Select One">Select One</option>
<option value="0.1">A</option>
<option value="0.2">B</option>
<option value="0.3">C</option>
</select>
<br/>
<input
type="number"
name="sv_312"
size="10"
maxlength="10"
onblur="calculate()"
id="sv_312"
/>
Calculated value
<div id="coverage"> </div>
</form>
The javascript:
<script>
//define an array for the possible values input via select menu
var spv = new Array();
spv["A"]=0.1;
spv["B"]=0.2;
spv["C"]=0.3;
//function to get the value from select menu
function getSAMprevalence()
{
var SAMprevalence=0;
var theForm = document.forms["myform"];
var selectedSAMprevalence = theForm.elements["sv_313"];
SAMprevalence = spv[selectedSAMprevalence.value]
return SAMprevalence;
}
//function to get the value from input field
function getInputvalue()
{
var Inputvalue=0;
var theForm = document.forms["myform"];
var Inputvalue = theForm.elements["sv_312"];
return Inputvalue;
}
//function to calculate using these two functions, and output into div named coverage:
function calculate()
{
var treatmentCoverage = getSAMprevalence() + getInputvalue();
document.getElementById('coverage').innerHTML =
""+treatmentCoverage;
}
</script>
I am really not experienced with javacsript or anything really, any pointers would be very appreciated. Thanks!
EDIT: here is a jsfiddle with it set up in, illustrating the lack of any output :(
http://jsfiddle.net/rHu8J/3/
Try using jQuery ..
DEMO
$(function() {
$('#sv_313').on('change', function() {
calculate();
});
$('input[name=sv_312]').on('blur', function() {
calculate();
});
});
function calculate() {
var $select = $('#sv_313').val();
var $text = $('input[name=sv_312]').val();
if ($select == undefined || $select == '' ||$select == 'Select One') {
$select = 0;
}
else {
$select = parseFloat($select);
}
//
if ($text == undefined || $text == '') {
$text = 0;
}
else {
$text = parseFloat($text);
}
$('.coverage').html($select + $text);
}​
HTML:
<form id="myform">
<select name="sv_313" onchange="calculate()" id="sv_313">
<option value="0">Select One</option>
<option value="0.1">A</option>
<option value="0.2">B</option>
<option value="0.3">C</option>
</select>
<br/>
<input type="number" id="sv_312" size="10" maxlength="10" onchange="calculate()"/>
</form>
Calculated value
<div id="coverage"></div>
Javascript:
function calculate() {
var myForm = document.forms['myform'];
var selectVal = myForm.elements['sv_313'].value;
var inputVal = myForm.elements['sv_312'].value;
if(!inputVal) inputVal = 0;
document.getElementById('coverage').innerHTML = parseFloat(selectVal) + parseInt(inputVal);
}
I believe your error is when you get the selected option. Try this instead:
SAMprevalence = spv[selectedSAMprevalence.options[selectedSAMprevalence.selectedIndex].text]
thanks to:
Get selected value in dropdown list using JavaScript?

Categories