can't add elements from form, using getElementByID - javascript

I can't seem to get my JavaScript to add the elements from my HTML page. Do I have a syntax error?
var mondayHours = document.getElementById("mondayHours").value;
var tuesdayHours = document.getElementById("tuesdayHours").value;
var wednesdayHours = document.getElementById("wednesdayHours").value;
var thursdayHours = document.getElementById("thursdayHours").value;
var fridayHours = document.getElementById("fridayHours").value;
var saturdayHours = document.getElementById("saturdayHours").value;
var sundayHours = document.getElementById("sundayHours").value;
var totalHours = mondayHours + tuesdayHours + wednesdayHours + thursdayHours + fridayHours + saturdayHours + sundayHours;
function alertHours() {
alert(totalHours);
}
<fieldset>
<p>Hours of Operation</p>
<p>
<label for="mondayHours">Monday
<input name="mondayHours" type="number" id="mondayHours" />
</label>
</p>
<p>
<label for="tuesdayHours">Tuesday
<input name="tuesdayHours" type="number" id="tuesdayHours" />
</label>
</p>
<p>
<label for="wednesdayHours">Wednesday
<input name="wednesdayHours" type="number" id="wednesdayHours" />
</label>
</p>
<p>
<label for="thursdayHours">Thursday
<input name="thursdayHours" type="number" id="thursdayHours" />
</label>
</p>
<p>
<label for="fridayHours">Friday
<input name="fridayHours" type="number" id="fridayHours" />
</label>
</p>
<p>
<label for="saturdayHours">Saturday
<input name="saturdayHours" type="number" id="saturdayHours" />
</label>
</p>
<p>
<label for="sundayHours">Sunday
<input name="sundayHours" type="number" id="sundayHours" />
</label>
</p>
</fieldset>
<input name="Calculate" type="submit" value="submit" onclick="alertHours()" />
<script src="Calculator_script.js"></script>

You have to retrieve form data when you called your alertHours function.
The problem was that you retrieved form data at the beginning, and these data were undefined.
JS
function alertHours(){
var mondayHours = parseFloat(document.getElementById("mondayHours").value) || 0;
var tuesdayHours = parseFloat(document.getElementById("tuesdayHours").value) || 0;
var wednesdayHours = parseFloat(document.getElementById("wednesdayHours").value) || 0;
var thursdayHours = parseFloat(document.getElementById("thursdayHours").value ) || 0;
var fridayHours = parseFloat(document.getElementById("fridayHours").value) || 0;
var saturdayHours = parseFloat(document.getElementById("saturdayHours").value ) || 0;
var sundayHours = parseFloat(document.getElementById("sundayHours").value) || 0;
var totalHours = mondayHours + tuesdayHours + wednesdayHours + thursdayHours + fridayHours + saturdayHours + sundayHours;
alert(totalHours)
}
When you see parseFloat(...) || 0, this tell : ok if an input is empty, i will set the 0 value for this input.

You are grabbing the values on page load and storing those in variables. Since at that time, they are valueless, you aren't getting your expected result. I would recommend the following option...
var mondayHours = document.getElementById("mondayHours");
var tuesdayHours = document.getElementById("tuesdayHours");
var wednesdayHours = document.getElementById("wednesdayHours");
var thursdayHours = document.getElementById("thursdayHours");
var fridayHours = document.getElementById("fridayHours");
var saturdayHours = document.getElementById("saturdayHours");
var sundayHours = document.getElementById("sundayHours");
function alertHours() {
var totalHours = mondayHours.value + tuesdayHours.value + wednesdayHours.value + thursdayHours.value + fridayHours.value + saturdayHours.value + sundayHours.value;
alert(totalHours);
}
This way you are getting the values of the inputs at the time the function is invoked, and not the time that the page was loaded. And scoping the getElementById outside of the alertHours function still gives you access to those elements should you need to use them somewhere else in code. There are more clever/eloquent ways to do this still, but this should work.

Related

Calculate total sum of all the numbers previously entered in a field

i want to calculate the total of the numbers entered by the user. After a user has added item name and the amount, i want to display the total. How can i do this? i just need to display the total.
For example
item name : 10
item name : 5
total = 15
http://jsfiddle.net/81t6auhd/
<body>
<header>
<h1>Exercise 5-2</h1>
</header>
<p>Item: <input type="text" id="item" size="30">
<p>Amount: <input type="text" id="amount" size="30">
<p><span id="message">*</span>
<p><input type="button" id="addbutton" value="Add Item" onClick="processInfo();">
<script>
var $ = function(id) {
return document.getElementById(id);
};
var myTransaction = [];
function processInfo ()
{
var myItem = $('item').value;
var myAmount = parseFloat($('amount').value);
var myTotal = myItem + ":" + myAmount;
var myParagraph = $('message');
myParagraph.innerHTML = "";
myTransaction.push(myTotal);
myParagraph.innerHTML += myTransaction.join("<br>");
};
(function () {
$("addbutton").onclick = processInfo;
})();
</script>
</body>
you have to stored the previous value somewhere in memory to be able to reuse it at next iteration
one proposal can be to stored it in dataset of the field
if ($('amount').dataset.previous) {
myAmount += parseFloat($('amount').dataset.previous);
}
$('amount').dataset.previous = myAmount
var $ = function(id) {
return document.getElementById(id);
};
var myTransaction = [];
function processInfo ()
{
var myItem = $('item').value;
var myAmount = parseFloat($('amount').value);
if ($('amount').dataset.previous) {
myAmount += parseFloat($('amount').dataset.previous);
}
$('amount').dataset.previous = myAmount;
var myTotal = myItem + ":" + myAmount;
var myParagraph = $('message');
myParagraph.innerHTML = "";
myTransaction.push(myTotal);
myParagraph.innerHTML += myTransaction.join("<br>");
};
(function () {
$("addbutton").onclick = processInfo;
})();
<p>Item: <input type="text" id="item" size="30">
<p>Amount: <input type="text" id="amount" size="30">
<p><span id="message">*</span>
<p><input type="button" id="addbutton" value="Add Item" onClick="processInfo();">

Math through multiple inputs

getting no errors but trying to loop through all the inputs and add them all to the total (var = paidTotal). The first input works but the rest don't when others are added with an add button. Something wrong with the loop?
$(document).ready(function() {
var maxFields = 20;
var addButton = $('#plusOne');
var deleteButton = $('#minusOne');
var wrapper = $('#userNumbers');
var fieldInput = '<div><input type="text" name="persons" id="persons"/></div>';
var x = 1;
$(addButton).click(function () {
if (x < maxFields) {
x++;
$(wrapper).append(fieldInput);
}
});
$(deleteButton).click(function(e) {
e.preventDefault();
var myNode = document.getElementById("userNumbers");
i=myNode.childNodes.length - 1;
if(i>=0){
myNode.removeChild(myNode.childNodes[i]);
x--;
}
});
});
function peoplePaid() {
var checkTotal = document.getElementById('check').value;
var personsCheck = document.getElementById('personsCheck').value;
var paidTotal = document.getElementById('paidTotal');
for(var i = 1; i < personsCheck.length; i+=1){
personsCheck[i] += paidTotal;
}
paidTotal.innerHTML = checkTotal - personsCheck;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$ <input type="text" id="check" value="" />
<button type="button" id="plusOne">+</button>
<button type="button" id="minusOne">-</button>
<div id="userNumbers">
<div class="">
<input type="text" id="personsCheck" name="person">
</div>
<button onclick="peoplePaid()">Calculate</button>
<!--Paid Amount-->
<div>
<h3>Paid Amount: <span id="paidTotal"></span></h3>
</div>
make it as class
<input type="text" class="personsCheck" name="person">
and access it by
var personsCheck = document.getElementsByClassName('personsCheck');
ids have to be unique. You'll only get one element from document.getElementById().
Try using a class instead, something like
var fieldInput = '<div><input type="text" name="persons" class="persons"/></div>';
and use document.getElementsByClassName('persons') to get an array of all of the input fields that have that class.
Your code logic is not something what you want to achieve.
I can not find any logic to use the input element with id=personsCheck.
First of all, you are appending input element with same id again and again which is invalid, because in a document id attribute must be unique. Use class attribute instead.
To get the total you can first get the elements with querySelectorAll(), theb use forEach() to loop through all of them to add one by one.
$(document).ready(function() {
var maxFields = 20;
var addButton = $('#plusOne');
var deleteButton = $('#minusOne');
var wrapper = $('#userNumbers');
var fieldInput = '<div><input type="text" name="persons" class="persons"/></div>';
var x = 1;
$(addButton).click(function () {
if (x < maxFields) {
x++;
$(wrapper).append(fieldInput);
}
});
$(deleteButton).click(function(e) {
e.preventDefault();
var myNode = document.getElementById("userNumbers");
i=myNode.childNodes.length - 1;
if(i>=0){
myNode.removeChild(myNode.childNodes[i]);
x--;
}
});
});
function peoplePaid() {
var checkTotal = Number(document.getElementById('check').value);
var persons = document.querySelectorAll('.persons');
var personsCheck = Number(document.getElementById('personsCheck').value)
var paidTotal = document.getElementById('paidTotal');
var total = 0;
persons.forEach(function(p){
total += Number(p.value);
});
paidTotal.textContent = checkTotal - total;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$ <input type="text" id="check" value="" />
<button type="button" id="plusOne">+</button>
<button type="button" id="minusOne">-</button>
<div id="userNumbers">
<div class="">
<input type="text" id="personsCheck" name="person">
</div>
<button onclick="peoplePaid()">Calculate</button>
<!--Paid Amount-->
<div>
<h3>Paid Amount: <span id="paidTotal"></span></h3>
</div>

Add values from input to array on button click

I have 3 bootstrap sliders, which are basically input fields. The values of these sliders get displayed into an input box, and below that a price value is displayed. What I need to do is to save those 4 values to an array whenever a button is clicked. I managed to do this with the values hardcoded and without a button like this:
<li> <a class = "add-to-cart" href = "#" data-name = "Windows" data-price = "99.95" data-ram ="1" data-diskSpace="30" data-cpu="3">
<script>
$(".add-to-cart").click(function(event){
event.preventDefault(); // prevents the links from doing their default behaviour
var name = $(this).attr("data-name");
var price = Number($(this).attr("data-price"));
var ram = Number($(this).attr("data-ram"));
var diskSpace =Number($(this).attr("data-diskSpace"));
var cpu = Number($(this).attr("data-cpu"));
addItemToCart(name,price,1,ram,diskSpace,cpu);
displayCart();
});
var cart = [];
var Item = function (name,price,quantity,ram,diskSpace,cpu){
this.name = name;
this.price = price;
this.quantity = quantity;
this.ram = ram;
this.diskSpace = diskSpace;
this.cpu = cpu;
};
//addItemToCart(name,price,quantity)
function addItemToCart(name,price,quantity,ram,diskSpace,cpu){
for (var i in cart){
if(cart[i].name === name){
cart[i].quantity +=quantity;
saveCart();
return;
}
}
var item = new Item(name,price,quantity,ram,diskSpace,cpu);
cart.push(item);
}
</script>
This is my code for the values from the input box :
<input class="slider" id="ram" data-slider-id='ex1Slider' type="text" data-slider-min="0" data-slider-max="10" data-slider-step="1" />
<hr />
<input class="slider" id="diskSpace" data-slider-id='ex1Slider2' type="text" data-slider-min="0" data-slider-max="100" data-slider-step="10" />
<hr />
<input class="slider" id="cpu" data-slider-id='ex1Slider3' type="text" data-slider-min="0" data-slider-max="4" data-slider-step="1" />
<hr />
<input type="text" class="form-control" id="inputValue" value="0" />
</div>
Prijs:
<div id = "prijs">
</div>
<script>
var minSliderValue = $("#ram").data("slider-min");
var maxSliderValue = $("#ram").data("slider-max");
$('#ram').slider({
value : 0,
formatter: function(value) {
return 'RAM: ' + value + 'GB';
}
});
$('#diskSpace').slider({
value : 0,
formatter: function(value) {
return 'Disk Space: ' + value + 'GB';
}
});
$('#cpu').slider({
value : 0,
formatter: function(value) {
return 'CPU : ' + value + ' Cores';
}
});
// If You want to change input text using slider handler
$('#ram, #diskSpace, #cpu').on('slide', function(slider){
var ram = parseFloat($('#ram').val());
var diskSpace = parseFloat($('#diskSpace').val());
var cpu = parseFloat($('#cpu').val());
$("#inputValue").val("RAM="+ ram + "GB, Disk=" +diskSpace + "GB, Core="+cpu);
var totalPrice=(parseFloat(ram)*3.5 + parseFloat(diskSpace)*0.15+ parseFloat(cpu)*6.5).toFixed(2);
$("#prijs").html(totalPrice);
});
</script>
working jsfiddle for the sliders function: http://jsfiddle.net/umxhhqy4/8/

Nn algorithm that divides a single number three times Javascript

I'm trying to create an algorithm that divides a single number three times.
I've created this code, but it for some reason it doesn't work and I've got no clue why.
Could some one give me insight into what i'm doing wrong?
HTML
<form id="frm1">
Budget: <input id="budget" type="text" name="budget" value="110"><br>
<br>
Domestic:
<input id="low" type="text" name="low" value="20">%<br>
<input id="lowresult" type="text" name="low" oninput="calculate()"><br>
Continental:
<input id="med" type="text" name="med" value="30">% <br>
<input id="medresult" type="text" name="med" oninput="calculate()"><br>
International:
<input id="high" type="text" name="high" value="50">% <br>
<input id="highresult" type="text" name="high" oninput="calculate()"><br>
<br>
</form>
Javascript
function calculate() {
var budget = document.getElementById("budget").value;
var low = document.getElementById('low').value;
var med = document.getElementById('med').value;
var high = document.getElementById('high').value;
var lowResult = document.getElementById('lowresult');
var medResult = document.getElementById('medresult');
var highResult = document.getElementById('highresult');
var lowFinalResult = (budget /100)*low;
lowResult.value = lowResult;
var medFinalResult = (budget /100)*med;
medResult.value = medResult;
var highFinalResult = (budget /100)*high;
highResult.value = highResult;
}
adjust javascript
this
var lowFinalResult = (budget /100)*low;
lowResult.value = lowFinalResult;
insetad of
var lowFinalResult = (budget /100)*low;
lowResult.value = lowResult;
full code
function calculate() {
var budget = document.getElementById("budget").value;
var low = document.getElementById('low').value;
var med = document.getElementById('med').value;
var high = document.getElementById('high').value;
var lowResult = document.getElementById('lowresult');
var medResult = document.getElementById('medresult');
var highResult = document.getElementById('highresult');
var lowFinalResult = (budget /100)*low;
lowResult.value = lowFinalResult;
var medFinalResult = (budget /100)*med;
medResult.value = medFinalResult;
var highFinalResult = (budget /100)*high;
highResult.value = highFinalResult;
}
You wrote in the comment that you're "trying to input one amount into the 'budget' input". So I'd like to add that you do that calculate() in the budget input:
<form id="frm1">
Budget: <input id="budget" type="text" name="budget"
value="110" oninput="calculate()"><br>
So the oninput attribute of the other inputs can be removed.

Counting number of inputs filled

I have 4 inputs on a form and I want to do a calculation based on the number of inputs filled.
I have come up with this and it works in IE but not in FF. FF doesnt seem to like the multiple document.getElementById. Any help would be appreciated.
<script type="text/javascript" language="javascript">
function countlines(what) {
var headline = 1 ;
var oneline = 1 ;
var twoline = 1 ;
var webline = 1 ;
var valhead = document.getElementById('adverttexthead').value;
if (/^\s*$/g.test(valhead) || valhead.indexOf('\n') != -1)
{var headline = 0};
var valone = document.getElementById('adverttextone').value;
if (/^\s*$/g.test(valone) || valone.indexOf('\n') != -1)
{var oneline = 0};
var valtwo = document.getElementById('adverttexttwo').value;
if (/^\s*$/g.test(valtwo) || valtwo.indexOf('\n') != -1)
{var twoline = 0};
var valweb = document.getElementById('adverttextweb').value;
if (/^\s*$/g.test(valweb) || valweb.indexOf('\n') != -1)
{var webline = 0};
(document.getElementById('webcost').value = "$" + ((headline + oneline + twoline + webline) * 16.50).toFixed(2));
(document.getElementById('totallines').value = headline + oneline + twoline + webline);
}
</script>
HTML
<input name="adverttexthead" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<br>
<input name="adverttextone" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<br>
<input name="adverttexttwo" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<br>
<input name="adverttextweb" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<input name="totallines" id="totallines" size="4" readonly="readonly" type="text">
<input name="webcost" id="webcost" size="6" readonly="readonly" type="text">
You could put the inputs in a form and do like so:
function countFormElements(formNumber){
var fn = !formNumber ? 0 : formNumber;
var frm = document.getElementsByTagName('form')[fn], n = 0;
for(var i=0,l=frm.length; i<l; i++){
if(frm.elements[i].value !== '')n++;
}
return n;
}
console.log(countFormElements());
You did not set the 'id' attribute on some elements
You reinitialized your variables in the 'if' clauses.
Working code:
<input id="adverttexthead" name="adverttexthead" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<br>
<input id="adverttextone" name="adverttextone" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<br>
<input id="adverttexttwo" name="adverttexttwo" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<br>
<input id="adverttextweb" name="adverttextweb" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<input id="totallines" name="totallines" size="4" readonly="readonly" type="text">
<input id="webcost" name="webcost" size="6" readonly="readonly" type="text">
function countlines(what) {
var headline = 1;
var oneline = 1;
var twoline = 1;
var webline = 1;
var valhead = document.getElementById('adverttexthead').value;
if (/^\s*$/g.test(valhead) || valhead.indexOf('\n') != -1) {
headline = 0
};
var valone = document.getElementById('adverttextone').value;
if (/^\s*$/g.test(valone) || valone.indexOf('\n') != -1) {
oneline = 0
};
var valtwo = document.getElementById('adverttexttwo').value;
if (/^\s*$/g.test(valtwo) || valtwo.indexOf('\n') != -1) {
twoline = 0
};
var valweb = document.getElementById('adverttextweb').value;
if (/^\s*$/g.test(valweb) || valweb.indexOf('\n') != -1) {
webline = 0
};
(document.getElementById('webcost').value = "$" + ((headline + oneline + twoline + webline) * 16.50).toFixed(2));
(document.getElementById('totallines').value = headline + oneline + twoline + webline);
}
Here is a working jsFiddle: http://jsfiddle.net/YC6J7/1/
You'll need to set the id attribute for the inputs as well as the name, otherwise getElementById works inconsistently cross browser.
For instance:
<input id="adverttexthead" name="adverttexthead" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
(Technically name is optional for purposes of document.getElementById, since id is accepted pretty universally, but you'll probably want to keep it so your forms submit correctly.)
For more details, see: Document.getElementById() returns element with name equal to id specified

Categories