I am using bracket editor when I save the bill.js editor show some
error at every document the desired output is not coming.
HTML code is
<!DOCTYPE html>
<html lang="en">
<head>
<title>split Bill</title>
<link rel="stylesheet" type="text/css" href="normalize.css">
<link rel="stylesheet" type="text/css" href="splitbill.css">
</head>
<body>
<div id="container">
<h1>Bill calculator</h1>
<div id="calculator">
<form>
<label>
How Much your Bill ? <br>
Rupees <input type="text" id="billAmount">
</label>
<label>
How was your Service sir?<br>
<select id="serviceFeedback">
<option disabled selected value="0">
--Choose an option--
</option>
<option value="0.4">
40% -Very Good
</option>
<option value="0.3">
30% - Good
</option>
<option value="0.2">
20% - it was Ok
</option>
<option value="0.1">
10% - Bad
</option>
<option value="0.05">
5% - poor
</option>
</select>
</label>
<label>
How many people sharing the bill?<br>
<input type="text" id="totalpeople">
people
</label>
<button type="button" id="calculate">calculate!</button>
</form>
</div>
<div id="totalTip">
<sup>Rupees</sup><span id="tip">0.00 </span>
<small id="each">each</small>
</div>
</div>
<script type="text/javascript" src="bill.js"></script>
</body>
</html>
javascript is here I didn't get desired output at every document function there is error sign please tell me what I do I am using bracket editor.
why I got this I am using
at the end of HTML code
//create function
function calculateTip() {
var billAmount = document.getElementById("billAmount").value;
var serviceFeedback = document.getElementById("serviceFeedback").value;
var numpeople =document.getElementById("totalpeople").value;
//validation
if (billAmount =="" ||serviceFeedback == 0) {
window.alert("please enter some value Boss!");
return;
}
//if input is empty
if (numpeople =="" ||numpeople <= 1) {
numpeople =1;
document.getElementById("each").style.display ="none";
} else {
document.getElementById("each").style.display ="block";
}
var total = (billAmount * serviceFeedback) / numpeople;
total = Math.round(total * 100) / 100;
total = total.toFixed(2);
//display the tip
document.getElementById("totalTip").style.display = "block";
document.getElementById("tip").innerHTML = total;
}
// hide tip amount
document.getElementById("totalTip").style.display ="none";
document.getElementById("each").style.display ="none";
//clicking the button calls our custom function
document.getElementById("calculate").onclick=function()
{
calculateTip();
}
In the function "calculateTip" I found the line:
if (billAmount =="" || ServiceFeedback == 0) {
Here ServiceFeedback starts with a capital letter instead of a lower case letter.
The selected option of a select-Field you get like that:
let selectElement = document.getElementById("serviceFeedback");
let serviceFeedback = selectElement.option[selectElement.selectedIndex].value;
In the html file I found an other problem:
<input type="text" id="totalpeople ">
There is a blank at the end of the id! Better would be:
<input type="text" id="totalpeople">
In the javascript file there is an other blank:
document.getElementById("each").style.display = " none";
Better would be:
document.getElementById("each").style.display = "none";
I hope that helps.
To ReferenceError: document is not defined I found that:
ReferenceError: document is not defined (in plain JavaScript)
=> My questions are:
What does bill.js contain?
Where is calculateTip() called?
I mean: Is anywhere a call like that document.getElementsBy... before the document is created?
I was trying to make a content score as a class assignment.
Assume : (The user sees a URL and then select the checkboxes that are assigned to issues . Each issue is assigned a score in a array.)
Whats working :
Individual checks are registered with their respective scores being displayed
Whats not working :
Can someone help me to update the score ( as the user checks the checkbox or unchecks).
I am assuming in future if i want to increase the issues I will be able to do that since it is in an array. (am i right)
(my week 4 in JS)
//Set up an array with the respective score
var code = new Array();
code["v1"] = 1;
code["v2"] = 2;
code["v3"] = 3;
code["v4"] = 5;
// As the user selects the checkbox I want to keep on adding the score and as the user unchecks I want to recalculate and display.
function getvalueScore() {
var score = 0;
//Get a reference to the form
var theForm = document.forms["contentForm"];
//Get a reference to the score from the "ContentForm"
var contentScore = theForm.elements["contentScore"];
// loop through each check box
for (var i = 0; i < contentScore.length; i++) {
//if the radio button is checked
if (contentScore[i].checked) {
// I want to calculate and keep updating the score
score = code[contentScore[i].value];
}
}
//return score
return score;
}
function calculateTotal() {
//calculation for final score
var scoreCard = getvalueScore();
//display the result
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'block';
divobj.innerHTML = "Your Content Score is " + scoreCard;
}
function hideTotal() {
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'none';
}
<!DOCTYPE html>
<html>
<head>
<title>Content Score</title>
<meta charset="utf-8">
<script src="formcalculations.js"></script>
</head>
<body onload='hideTotal()'>
<div id="wrap">
<form action="" id="contentForm" onsubmit="return false;">
<div>
<div class="cont_order">
Content Score</br>
<label>Please select the issues you see on the page to calculate the content score</label>
</br>
<label class='radiolabel'>
<input type="checkbox" name="contentScore" value="v1" onclick="calculateTotal()" />No content value</label>
<br/>
<label class='radiolabel'>
<input type="checkbox" name="contentScore" value="v2" onclick="calculateTotal()" />Mediocre content value</label>
<br/>
<label class='radiolabel'>
<input type="checkbox" name="contentScore" value="v3" onclick="calculateTotal()" />Obsolete content</label>
<br/>
<label class='radiolabel'>
<input type="checkbox" name="contentScore" value="v4" onclick="calculateTotal()" />Irrelevant content</label>
<br/>
<br/>
<br/>
<div id="totalPrice"></div>
</div>
</div>
</form>
</div>
<!--End of wrap-->
</body>
</html>
In your code you assign last selected checkbox to score variable, so the only thing you need to do is to sum the scores with:
score += code[contentScore[i].value];
I am trying to test a java script function the purpose of the function is to get the value of a user selected form element. Specifically a radio button. my goal is to use this function in another function to calculate a price total. But for now, I just want to make sure this function returns the value of the selected radio button.
<html>
<head>
</head>
<body>
<form name="testForm">
<legend>Calculate your square feet</legend>
</br>
<label> What size plants are you starting with ? </label>
</br>
</br>
<input type="radio" name="plantType" value="16"/>Seeds, havn't started yet</label>
</br>
<input type="radio" name="plantType" value="16"/> Seedlings, less than 2ft high</label>
</br>
<input type="radio" name="plantType" value="32"/> Juvenile, 2 - 4ft high</label>
</br>
<input type="radio" name="plantType" value="64"/> Adult, 4ft or higher</label>
</br>
</form>
<script type="text/javascript">
var plant_name = new Array();
plant_name[16] = 16;
plant_name[16] = 16;
plant_name[32] = 32;
plant_name[32] = 64;
function getPlantSize() {
var plantSize = 0;
var theForm = document.testForm;
var selectedPlant = theForm.plantType;
for (var i = 0; i < plantType.length; i++)
{
if (plantType[i].checked)
{
plantSize = plant_name.[selectedPlant[i].value];
break;
}
document.write (plantSize);
}
}
</script>
</body>
</html>
Currently working on an "retirement calculator" where I have to generate a table for money-saved each year based on data entered into the first two forms. Unfortunately I can't figure out why it's not appending the table to the site. I don't receive any errors on the console.
I'm also a complete novice at JS/JQ. The code for calculate is near the bottom. I realize it may look at little all over the place, I'm trying to get it to work first before I got back and clean it up some.
EDIT: I took out some methods so there isn't so much to traverse. Assume that the variables involved in calculate are set to real values (aka they're not null/NaN).For example there's an add JQuery method that'll add more scenarios. But since it distracts from the problem I took it out. But the for loop runs in relation to the array
var scenarioCount=0;
var hasError=false
var error=false;
var YOB;
var CurrSav;
var RetAge;
var LifeExp;
var Year;
var scenarios = new Array();
$(document).ready(function ()
{
$('#calculate').on('click', function(e)
{
if(!isBasicInfoValid()) //check to see if basic info is correct
{
if(!error) //if there isn't already an error put one
{
$('#basic').append($("<div class='basicError'>Input is not valid! </div>"));
}
resetVars(); //reset the variables
error=true; //say there is an error on screen
}
else
{
$("#basic .basicError").remove();
error=false;
calculate();
}
e.preventDefault();
});
});
function calculate()
{
var body = document.getElementById('body');
//body is null right here for some reason
$(body).append("<div id='results' class='form'>");
for(var i=0;i<scenarios.length;i++)
{
var element = scenarios[i];
var n = parseInt(YOB)+parseInt(RetAge)-Year;
var m = LifeExp-RetAge;
var r = 1+element.workRate;
var g = 1 + element.retiredRate;
var I = CurrSav;
var T = element.retIncome;
var part1 = (T/Math.pow(g,m-1))*((1-Math.pow(g,m))/(1-g))-(I*Math.pow(r,n));
var S = part1*(1-r)/(1-Math.pow(r,n));
var savings=I;
$('#results').append("<div><h4>You need to save "+S+" dollars</h4></div>")
$('#results').append("<table id=t><tr><th>Year</th><th>Money Saved</th></tr>");
for(var j=n;j>0;j--)
{
savings=S+savings*r;
$('#t').append("<tr><td>"+j+"</td><td>"+savings+"</td></tr>")
}
for(var j=m;j>0;j--)
{
savings=(savings-T)*g;
$('#t').append("<tr><td>"+j+"</td><td>"+savings+"</td></tr>")
}
$('#results').append("</table></div>");
}
};
function resetVars()
{
YOB=null;
CurrSav=null;
RetAge=null;
LifeExp=null;
Year=null;
}
function scenarioObject()
{
var obj={
nameScen : document.forms["scenario"]["ScenarioName"].value,
workRate : document.forms["scenario"]["Working"].value,
retiredRate : document.forms["scenario"]["Retired"].value,
retIncome : document.forms["scenario"]["desiredInc"].value
}
return obj;
}
<!DOCTYPE html>
<html>
<head>
<title>Assignment 3</title>
<link rel='stylesheet' type='text/css' href='/uncSemester7/comp426/a3/assignment3.css'>
<script src='/uncSemester7/comp426/a3/jquery-1.10.2.js'></script>
<script src='/uncSemester7/comp426/a3/assignment3.js'></script>
</head>
<body>
<div class='form'>
<h3> Basic Information </h3>
<form id='basic'>
<div>Year of Birth: <input type='number' name='YOB'> </div>
<div>Current Savings: <input type='number' name='CurrSav'>
</div>
<div>Expected Retirement Age: <input type='number' name='RetAge'></div>
<div>Life expectancy: <input type='number' name='LifeExp'>
</div>
</form>
</div>
<div id='scenDiv' class='form'>
<div id='buttons'>
<div><button id='add' type='submit'>Add Scenario </button></div>
<div><button id='calculate' type='submit'> Calculate </button></div>
</div>
<h3> Scenario </h3>
<form id='scenario'>
<div>Name: <input type='text' name='ScenarioName'> </div>
<div>Rate of Investment Return (While Working): <input type='number' name='Working'></div>
<div>Rate of Investment Return (Retired): <input type='number' name='Retired'></div>
<div>Desired Retirement Yearly Income: <input type='number' name='desiredInc'></div>
</form>
</div>
</body>
</html>
You're using getElementById('body'), where you should be using getElementsByTagName('body')[0], as body is not an id, but a tag. Or better yet with jQuery since you're already using it, $('body').
Look at this HTML example:
<html>
<head>
<title>My Page</title>
</head>
<body>
<form name="myform" action="http://www.mydomain.com/myformhandler.jsp" method="POST">
<div align="center"><br>
<input type="checkbox" name="option1" value="Milk"> Milk<br>
<input type="checkbox" name="option2" value="Butter" checked> Butter<br>
<input type="checkbox" name="option3" value="Cheese"> Cheese<br>
<br>
</div>
</form>
</body>
</html>
And the resulting output from it:
I hope to send the checked checkbox to the servlet, but i also want to get the order user selected these checkbox.
For example,user A do stuff like : select Cheese,select Butter, select Milk->then Cheese,Butter,Milk will be sent to servlet with this order.
If user B do stuff like : select Cheese,select Butter, deselect Butter, select Milk , select Butter->then Cheese,Milk,Butter will be sent to servlet with this order.
Appreciate.
Check the fiddle for the checkbox order here
I used the following JS Code
checkedOrder = []
inputList = document.getElementsByTagName('input')
for(var i=0;i<inputList.length;i++) {
if(inputList[i].type === 'checkbox') {
inputList[i].onclick = function() {
if (this.checked) {
checkedOrder.push(this.value)
} else {
checkedOrder.splice(checkedOrder.indexOf(this.value),1)
}
console.log(checkedOrder)
}
}
}
Make a global variable to track the order:
var selectOrder = 0;
Bind this function to your onclick event in your inputs:
function onClickHandler() {
var senderId = this.id;
selectOrder = selectOrder + 1;
document.getElementById(senderId).setAttribute('data-order', selectOrder);
}
That will set a data-* (custom) attribute on each one with the order they were checked. So, when you submit your form, you can grab all of the checkboxes and get the order with .getAttribute('data-order'); Don't forget to reset your selectOrder = 0 when you submit so it will reorder them on the next time through.
Try this code.This works better
<html>
<head>
<title>My Page</title>
<script type="text/javascript">
var arr=new Array();
function fnc(myid)
{
if(document.getElementById(myid).checked == true)
{
arr.push(document.getElementById(myid).value);
alert(arr);
}
else
{
var item1=document.getElementById(myid).value;
for(i=0;i<2;i++)
{
if(arr[i]=item1)
{
found=i;
arr.splice(found,1);
}
}
}
}
</script>
</head>
<body>
<form name="myform" action="http://www.mydomain.com/myformhandler.jsp" method="POST">
<div align="center"><br>
<input type="checkbox" name="option1" value="Milk" id="Milk" onchange="fnc(this.id)"> Milk<br>
<input type="checkbox" name="option2" value="Butter" id="Butter" onchange="fnc(this.id)"> Butter<br>
<input type="checkbox" name="option3" value="Cheese" id="Cheese" onchange="fnc(this.id)"> Cheese<br>
<br>
</div>
</form>
</body>
</html>
Here, give this a try.
It maintains an array of all of the options' values, along with the order in which they were clicked. It handles the case where items are already checked when the page loads, by arbitrarily assigning them an increasing index for the order they were clicked in.
It handles items being unselected, it also can provide you with a little more info as a happy side-effect of the way I've done it. You can for instance get back values of 2, 3, 4 for selection order. If I load the page, then select Milk then cheese before unselecting then reselecting Butter, I get back the values 2,3,4 2,4,3 - I can straight away tell that the last selection made was Butter, and that it had previously been the first item selected. Likely useless, but an interesting consequence to me all the same.
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<style>
#myDiv
{
border: 1px solid black;
display: inline-block;
}
</style>
<script>
window.addEventListener('load', mInit, false);
function mInit()
{
var i, inputList = document.getElementsByTagName('input'), n = inputList.length;
var cbCount = 0;
var curOrder = 0;
for (i=0; i<n; i++)
{
if (inputList[i].type == 'checkbox')
{
cbCount++;
var cur = inputList[i];
cur.addEventListener('change', onCbChange, false);
var mObj = {val:cur.value, selOrder:0};
if (cur.checked)
{
mObj.selOrder = ++curOrder;
}
availOptions.push( mObj );
}
}
}
var availOptions = []; // an array to hold objects - { val, selOrder }
function getItem(value)
{
var i, n = availOptions.length;
for (i=0; i<n; i++)
{
if (availOptions[i].val == value)
return availOptions[i];
}
return null;
}
// just clear it's selOrder member
function mUnselect(value)
{
var Item = getItem(value);
Item.selOrder = 0;
}
// iterate through the list, find the highest value of selOrder, increment it and set this item's selOrder to that
function mSelect(value)
{
var i, n = availOptions.length;
var curMax=0;
for (i=0; i<n; i++)
{
if (availOptions[i].selOrder > curMax)
curMax = availOptions[i].selOrder;
}
curMax++;
getItem(value).selOrder = curMax;
}
function onCbChange()
{
if (this.checked)
mSelect(this.value);
else
mUnselect(this.value);
alert(this.value + ': ' + this.checked);
}
function showCurState()
{
var i, n=availOptions.length;
var mStr = '';
for (i=0; i<n; i++)
mStr += availOptions[i].val + ", selOrder: " + availOptions[i].selOrder + "\n"
alert(mStr);
}
</script>
</head>
<body>
<div id='myDiv' align="left">
<br>
<input type="checkbox" name="option1" value="Milk"> Milk<br>
<input type="checkbox" name="option2" value="Butter" checked> Butter<br>
<input type="checkbox" name="option3" value="Cheese"> Cheese<br>
<br>
<input type='button' onclick='showCurState();' value='Show state'/>
</div>
</body>
</html>