Calculate difference of multiple inputs and write on page - javascript

I'm having an issue calculating the difference of two variables that should change depending on input values and number of inputs.
The jQuery works fine adding/subtracting buttons it's the peoplePaid() function that I've been dealing with.
I'm trying to write the difference (.difference) of paidTotal minus each input of pCheck.
So the first question is how do I get the value for difference (paidTotal - pCheck) to write to .difference for each input on the page.
And if I have to loop iy what may need to be done.
Thank you!
$(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 = parseFloat(document.getElementById('check').value);
var personsCheck = document.getElementsByClassName('persons');
var paidTotal = document.getElementById('paidTotal');
var serviceQuality = document.getElementById('serviceQuality').value;
var difference = document.getElementsByClassName('difference');
var pCheck = 0;
for (var i = 0; i < personsCheck.length; i += 1) {
pCheck += parseFloat(personsCheck[i].value);
}
paidTotal.innerHTML = (checkTotal * serviceQuality) - pCheck;
for (var i = 0; i < personsCheck.length; i += 1) {
checkDifference = parseFloat(paidTotal - pCheck).value;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Check Total</h3>
$ <input type="text" id="check" value="" />
<h3>Tip%</h3>
<select name="tip" id="serviceQuality">
<option disabled selected value="1">-- Choose an Option --</option>
<option value="1">0%</option>
<option value="1.06">6%</option>
<option value="1.15">15%</option>
<option value="1.2">20%</option>
<option value="1.3">30%</option>
</select>
<h3>Number of People: <span id="numberOfPeople"></span></h3>
<button type="button" onclick="plusOne()" id="plusOne">+</button>
<button type="button" onclick="minusOne()" id="minusOne">-</button>
<div>
<div id="userNumbers">
<input type="text" class="persons" name="person" />
<p class="difference">$</p>
</div>
</div>
<button onclick="peoplePaid()">Calculate</button>
<!--Paid Amount-->
<div>
<h3>Paid Amount: <span id="paidTotal"></span></h3>
</div>

Disscrepancies
There were some discrepancies that should be addressed:
(Major) There are two functions called by onclick event handlers:
<button type="button" onclick="plusOne()" id="plusOne">+</button>
<button type="button" onclick="minusOne()" id="minusOne">-</button>
First of all, a quick run of this Snippet logs errors about these functions not existing. Secondly, you should never use on-event handlers when using jQuery, it's like using paddle (on-event handlers) on a speed boat (event delegation using .on()).
(Minor) If you store jQuery Objects in variables, do not wrap those variables in $(...) because they already wrapped in $(...) when you declared them:
var addButton = $('#plusOne');
$(addButton).on('click',... // That is like doing this: $($('#plusOne'))
addButton.on('click',...... // This is the cleaner way or...
var $addButton = $('#plusOne');
$addButton.on('click'...... /* This is a common practice which serves as an obvious
reminder that the variable is a jQuery Object */
Plain JavaScript Array Methods
(Core) The solution is to collect all of the input.customer' by gathering the <input>s into a NodeList with .querySelctorAll() and then converting it into an array with Array.from():
var customers = Array.from(document.querySelectorAll('.customer'));
Next, use .map() to extract each of the <input>'s values, and then return them as an array:
var payments = customers.map(function(customer) {
return parseFloat(customer.value);
});
Finally, use .reduce() to add all of the values in the payments array into one number:
paidTotal = payments.reduce(function(total, number) {
return total + number;
});
Demo
var max = 20;
var count = 1;
var paidTotal = 0;
var customerQty = $('#totalCustomers');
var add = $('#add');
var group = $('.group');
var paid = `
<li>
<input type="number" class="customer" step='0.01'/>
<button type="button" class="remove">-</button>
</li>`;
add.on('click', function(e) {
if (count < max) {
count++;
group.append(paid);
} else {
return false;
}
customerQty.val(count);
});
group.on('click', '.remove', function() {
if (count > 0) {
count--;
var subtract = parseFloat($(this).prev('.customer').val()).toFixed(2);
var total = parseFloat($('#paidTotal').val()).toFixed(2);
var newTotal = parseFloat(total - subtract).toFixed(2);
$('#paidTotal').val(newTotal);
var due = parseFloat($('#balanceDue').val());
$('#balanceDue').val((due + parseFloat(subtract)).toFixed(2));
$(this).parent().remove();
} else {
return false;
}
customerQty.val(count);
});
$('#bill').on('input', totalPaid);
function totalPaid(e) {
var check = $('#check').val();
var tip = $('#tip').val();
var total = $('#paidTotal');
var due = $('#balanceDue');
var customers = Array.from(document.querySelectorAll('.customer'));
var payments = customers.map(function(customer) {
return parseFloat(customer.value);
});
//console.log('payments: '+payments);
paidTotal = payments.reduce(function(total, number) {
return total + number;
});
$('#amountDue').val(parseFloat(check * tip).toFixed(2));
//console.log('paidTotal: '+paidTotal);
total.val(parseFloat(paidTotal).toFixed(2));
due.val(parseFloat((check * tip) - total.val()).toFixed(2));
}
html {
font: 400 16px/1.5 Consolas;
}
body {
font-size: 1rem;
}
fieldset {
width: 490px;
}
button,
label,
select,
input,
output {
display: inline-block;
font: inherit;
line-height: 1.5;
}
label {
margin: 5px;
}
input {
width: 12ex;
text-align: center
}
button {
cursor: pointer;
}
output {
margin-left: -5px;
}
#totalCustomers {
font-size: 1.2rem;
color: blue;
}
#tip {
padding: 5px 0;
margin-left: -5px;
}
.tip {
margin-left: -2px;
}
.customers {
height: fit-content;
min-height: 60px;
}
.group {
margin: -8% 10px auto -25px;
padding-left: 1.5em;
width: 40%;
list-style-position: inside;
}
.group li {
padding-left: 0.1em;
}
.add {
transform: translate(105%, -15%);
}
/*
For debugging purposes only (Optional)
*/
.as-console-wrapper {
width: 250px;
min-height: 100%;
margin-left: 50%;
background: #000;
color: lime;
}
.as-console-row.as-console-row {
background: #000;
}
.as-console-row.as-console-row::after {
content: '';
padding: 0;
margin: 0;
border: 0;
width: 0;
}
<form id='bill'>
<fieldset class='total'>
<legend>Total Amount Due</legend>
$ <input type="number" id="check" value="" step='0.01' min='0.00'>
<label class='tip'>Tip%</label>
<select id="tip">
<option disabled selected value="">Pick</option>
<option value="1">0%</option>
<option value="1.06">6%</option>
<option value="1.15">15%</option>
<option value="1.2">20%</option>
<option value="1.3">30%</option>
</select>
<label>Amount Due: $
<output id="amountDue">0.00</output>
</label>
</fieldset>
<fieldset class='customers'>
<legend>Total Customers:
<output id="totalCustomers">1</output>
</legend>
<label class='add'> Add a Customer
<button type="button" id="add">+</button>
</label>
<ol class='group'>
<li>
<input type="number" class="customer" step='0.01' min='0.00' />
<button type="button" class="remove">-</button>
</li>
</ol>
</fieldset>
<fieldset class='grandTotal'>
<legend>Total Balance</legend>
<label>Paid Amount: $
<output id="paidTotal">0.00</output>
</label>
<br>
<label>Balance Due: $
<output id="balanceDue">0.00</output>
</label>
</fieldset>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

Set a field to required in html when an option is selected

Hi I am trying to make a field required when option is selected like if option 1 is selected so field one will be required and if option 2 then field 2 and make field 1 not required so on. So far I have tried setAttribute, removeAttribute, getelemenybyid(..).required=true or false (proper camel cases are used in code). nothing seem to work.to better explain I have entered the code below. I am using this form as Camunda embedded form and scripts are java scripts. smaple below
<div class="form-group" >
<label for="AmendmentType" >Amendment Type: </label>
<select class="form-control" onchange="Optionselection(this);" cam-variable-name="AmendmentType" cam-variable-type="String" id = "AmendmentType" required>
<option onClick="Optionselection()" id="update" name="AmendmentType" value="Update a field">Update a field</option>
<option onClick="Optionselection()" id="DuplicateId" name="AmendmentType" value="Duplicate Tax Files (to be mande inactive)">Duplicate Tax Files (to be made inactive)</option>
</select>
</div>
function Optionselection(that) {
if (that.value == "Update a field") {
document.getElementById('ValueinSystem').required=true;
document.getElementById('duplicateID').required=false;
}
else if(that.value == "Duplicate Tax Files (to be mande inactive)") {
document.getElementById('ValueinSystem').required=flase;
document.getElementById('duplicateID').required=true;
}
as i said i tried the following nothing seems to work
function Optionselection(that) {
if (that.value == "Update a field") {
document.getElementById('ValueinSystem').setAttribute('required','');
document.getElementById('duplicateID').removeAttribute('required');
}
else if(that.value == "Duplicate Tax Files (to be mande inactive)") {
document.getElementById('duplicateID').setAttribute('required','');
document.getElementById('ValueinSystem').removeAttribute('required');
}
Selects and makes the respective input field required, to distinguish added some style
More on client side validation here .......
const carsNode = document.querySelector("#cars");
const merc = document.querySelector("#merc");
const audi = document.querySelector("#audi");
const form = document.querySelector("form");
const mercError = document.querySelector('#merc + span.error');
const audiError = document.querySelector('#audi + span.error');
const carError = document.querySelector('#cars + span.error');
let selectedCar;
cars.addEventListener('change', (e) => {
// we listen to change event for select
selectedCar = e.target.value;
switch (selectedCar) {
case "mercedes":
merc.required = true;
audi.required = false;
break;
case "audi":
merc.required = false;
audi.required = true;
break;
default:
merc.required = false;
audi.required = false;
break;
}
})
form.addEventListener('submit', function(event) {
// if the field's is valid, we let the form submit
if ((!merc.validity.valid && selectedCar === "mercedes") || (!audi.validity.valid && selectedCar === "audi") || !selectedCar) {
// If it isn't, we display an appropriate error message
showError();
// Then we prevent the form from being sent by canceling the event
event.preventDefault();
}
});
function showError() {
if (merc.validity.valueMissing && selectedCar === "mercedes") {
// If the field is empty,
// display the following error message.
mercError.textContent = 'You need to enter a Mercedes value';
carError.textContent = '';
audiError.textContent = '';
// Set the styling appropriately
mercError.className = 'error active';
audiError.classList.remove('error', 'active');
carError.classList.remove('error', 'active');
} else if (audi.validity.valueMissing && selectedCar === "audi") {
audiError.textContent = 'You need to enter an Audi value';
mercError.textContent = '';
carError.textContent = '';
// Set the styling appropriately
audiError.className = 'error active';
mercError.classList.remove('error', 'active');
carError.classList.remove('error', 'active');
} else {
mercError.classList.remove('error', 'active');
audiError.classList.remove('error', 'active');
carError.textContent = 'You need to select a car';
mercError.textContent = '';
audiError.textContent = '';
carError.className = 'error active';
}
}
input:required {
border: 1px dashed red;
}
body {
font: 1em sans-serif;
width: 200px;
padding: 0;
margin: 10px auto;
}
p * {
display: block;
}
/* This is our style for the invalid fields */
input:invalid {
border-color: #900;
background-color: #FDD;
}
input:focus:invalid {
outline: none;
}
/* This is the style of our error messages */
.error {
width: 100%;
padding: 0;
font-size: 80%;
color: white;
background-color: #900;
border-radius: 0 0 5px 5px;
box-sizing: border-box;
}
.error.active {
padding: 0.3em;
margin-top: 5px;
}
input {
-webkit-appearance: none;
appearance: none;
width: 100%;
border: 1px solid #333;
margin: 0;
font-family: inherit;
font-size: 90%;
box-sizing: border-box;
}
<div>
<form novalidate>
<label for="cars">Choose a car:</label>
<select name="cars" id="cars">
<option value="" selected>Select Car</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<span class="error" aria-live="polite"></span>
<br>
<br>
<label for="merc">Mercedes:</label>
<input type="text" id="merc" name="merc">
<span class="error" aria-live="polite"></span>
<br><br>
<label for="audi">Audi:</label>
<input type="text" id="audi" name="audi">
<span class="error" aria-live="polite"></span>
<br><br>
<button>Submit</button>
</form>
</div>

How to change the text of a label when a radio button is selected

What I don't understand is why does my code not change the text of the label when the radio is selected?
This is what is suppose to happen:
Which when 'Fahrenheit to Celsius' is selected the first image should be true (the text of the first and second label should change)
When 'Celsius to Fahrenheit' is selected the second image should be true (the text of the first and second label should change)
What I'm guessing is my problem is with the if ($("input:to_celsius").val() == "true") statement but I don't quite know why it's wrong.
***Current error message:
{
"message": "Uncaught TypeError: Cannot set property 'onclick' of null",
"filename": "https://stacksnippets.net/js",
"lineno": 69,
"colno": 30
}
"use strict";
var $ = function(id) { return document.getElementById(id); };
var clearTextBoxes = function() {
$("#degrees_entered").value = "";
$("#degrees_computed").value = "";
};
window.onload = function() {
$("#to_celsius").onclick = toCelsius;
$("#to_fahrenheit").onclick = toFahrenheit;
$("#degrees_entered").focus();
};
// Change the text of label 1 and 2 when the radio 'Celsius to Fahrenheit' is selected and clears all other inputs
var toFahrenheit = function() {
if ($("#to_fahrenheit").val() == "true") {
$("#degree_labl_1").text("Enter C degrees");
$("#degree_label_2").text("Degrees Fahrenheit");
clearTextBoxes();
}
}
// Change the text of label 1 and 2 when the radio 'Fahrenheit to Celsius' is selected and clears all other inputs
var toCelsius = function() {
if ($("#to_celsius").val() == "true") {
$("#degree_labl_1").text("Enter F degrees");
$("#degree_label_2").text("Degrees Celsius");
clearTextBoxes();
}
}
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 450px;
border: 3px solid blue;
}
h1 {
color: blue;
margin: 0 0 .5em;
}
main {
padding: 1em 2em;
}
label {
float: left;
width: 10em;
margin-right: 1em;
}
input {
margin-bottom: .5em;
}
#convert {
width: 10em;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Convert Temperatures</title>
<link rel="stylesheet" href="styles.css">
<script src="convert_temp.js"></script>
<script src="jquery-3.4.1.min.js"></script>
</head>
<body>
<main>
<h1>Convert temperatures</h1>
<input type="radio" name="conversion_type" id="to_celsius" checked>Fahrenheit to Celsius<br>
<input type="radio" name="conversion_type" id="to_fahrenheit">Celsius to Fahrenheit<br><br>
<label id="degree_label_1">Enter F degrees:</label>
<input type="text" id="degrees_entered" ><br>
<label id="degree_label_2">Degrees Celsius:</label>
<input type="text" id="degrees_computed" disabled><br>
<label> </label>
<input type="button" id="convert" value="Convert" /><br>
</main>
</body>
</html>
There are multiple issues in your code.
Looks like you are trying to use jQuery here, but in your case you are overriding the jQuery $ function with a custom function. So in effect you are not using jQuery here by calling the $ function but using pure javascript selectors
var $ = function(id) {
return document.getElementById(id);
};
With a function declaration as above, you can select elements only by Id and the Id should not be prefixed with #
$("#degree_label_1") won't work here
$("degree_label_1") will work.
So I suggest changing the $ function declaration to something like below.
var $ = function(selector) {
return document.querySelector(selector);
};
Here I changed document.getElementById -> document.querySelector so that selectors are more flexible (You can use any css selectors like "#id", ".classname" etc)
As we are not using jQuery here, the below code will not work. In jQuery, its correct but there are syntax differences in accessing the dom in plain javascript
$("#to_fahrenheit").val() == "true"
One way to implement the same is..
Assign values to the radio button inputs
<input
type="radio"
name="conversion_type"
id="to_celsius"
value="f_to_c"
checked
/>Fahrenheit to Celsius<br />
<input
type="radio"
name="conversion_type"
id="to_fahrenheit"
value="c_to_f"
/>Celsius to Fahrenheit<br />
and check the value
$("#to_fahrenheit").value == "c_to_f"
Same applies to the below line. There's a typo as well (Missed an e in degree_label_1)
$("#degree_labl_1").text("Enter F degrees")
should be changed to
$("#degree_label_1").textContent = "Enter F degrees"
Complete code would look like below.
"use strict";
var $ = function(id) {
return document.querySelector(id);
};
var clearTextBoxes = function() {
$("#degrees_entered").value = "";
$("#degrees_computed").value = "";
};
window.onload = function() {
$("#to_celsius").onclick = toCelsius;
$("#to_fahrenheit").onclick = toFahrenheit;
$("#convert").onclick = convert;
$("#degrees_entered").focus();
};
// Change the text of label 1 and 2 when the radio 'Celsius to Fahrenheit' is selected and clears all other inputs
var toFahrenheit = function() {
if ($("#to_fahrenheit").value == "c_to_f") {
$("#degree_label_1").textContent = "Enter C degrees";
$("#degree_label_2").textContent = "Degrees Fahrenheit";
clearTextBoxes();
}
};
// Change the text of label 1 and 2 when the radio 'Fahrenheit to Celsius' is selected and clears all other inputs
var toCelsius = function() {
if ($("#to_celsius").value == "f_to_c") {
$("#degree_label_1").textContent = "Enter F degrees";
$("#degree_label_2").textContent = "Degrees Celsius";
clearTextBoxes();
}
};
var convert = function() {
var conversiontype = $(
'[name="conversion_type"]:checked'
).value;
var enteredValue = Number($("#degrees_entered").value);
if (conversiontype === "f_to_c") {
$("#degrees_computed").value = ((enteredValue - 32) * 5) / 9;
} else {
$("#degrees_computed").value = (enteredValue * 9) / 5 + 32;
}
};
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 450px;
border: 3px solid blue;
}
h1 {
color: blue;
margin: 0 0 0.5em;
}
main {
padding: 1em 2em;
}
label {
float: left;
width: 10em;
margin-right: 1em;
}
input {
margin-bottom: 0.5em;
}
#convert {
width: 10em;
}
<h1>Convert temperatures</h1>
<input
type="radio"
name="conversion_type"
id="to_celsius"
value="f_to_c"
checked
/>Fahrenheit to Celsius<br />
<input
type="radio"
name="conversion_type"
id="to_fahrenheit"
value="c_to_f"
/>Celsius to Fahrenheit<br /><br />
<label id="degree_label_1">Enter F degrees:</label>
<input type="text" id="degrees_entered" /><br />
<label id="degree_label_2">Degrees Celsius:</label>
<input type="text" id="degrees_computed" disabled /><br />
<label> </label>
<input type="button" id="convert" value="Convert" /><br />
If you want to use jQuery, you should remove below function declaration
var $ = function(id) {
return document.getElementById(id);
};
And modify your code as follows.
"use strict";
var clearTextBoxes = function() {
$("#degrees_entered").val("");
$("#degrees_computed").val("");
};
window.onload = function() {
$("#to_celsius").on("click", toCelsius);
$("#to_fahrenheit").on("click", toFahrenheit);
$("#convert").on("click", convert);
$("#degrees_entered").focus();
};
// Change the text of label 1 and 2 when the radio 'Celsius to Fahrenheit' is selected and clears all other inputs
var toFahrenheit = function() {
if ($("#to_fahrenheit").val() == "c_to_f") {
$("#degree_label_1").text("Enter C degrees");
$("#degree_label_2").text("Degrees Fahrenheit");
clearTextBoxes();
}
};
// Change the text of label 1 and 2 when the radio 'Fahrenheit to Celsius' is selected and clears all other inputs
var toCelsius = function() {
if ($("#to_celsius").val() == "f_to_c") {
$("#degree_label_1").text("Enter F degrees");
$("#degree_label_2").text("Degrees Celsius");
clearTextBoxes();
}
};
var convert = function() {
var conversiontype = $(
'[name="conversion_type"]:checked'
).val();
var enteredValue = Number($("#degrees_entered").val());
if (conversiontype === "f_to_c") {
$("#degrees_computed").val(((enteredValue - 32) * 5) / 9);
} else {
$("#degrees_computed").val((enteredValue * 9) / 5 + 32);
}
};
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 450px;
border: 3px solid blue;
}
h1 {
color: blue;
margin: 0 0 0.5em;
}
main {
padding: 1em 2em;
}
label {
float: left;
width: 10em;
margin-right: 1em;
}
input {
margin-bottom: 0.5em;
}
#convert {
width: 10em;
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<h1>Convert temperatures</h1>
<input type="radio" name="conversion_type" id="to_celsius" value="f_to_c" checked />Fahrenheit to Celsius<br />
<input type="radio" name="conversion_type" id="to_fahrenheit" value="c_to_f" />Celsius to Fahrenheit<br /><br />
<label id="degree_label_1">Enter F degrees:</label>
<input type="text" id="degrees_entered" /><br />
<label id="degree_label_2">Degrees Celsius:</label>
<input type="text" id="degrees_computed" disabled /><br />
<label> </label>
<input type="button" id="convert" value="Convert" /><br />

Simple Javascript Loop Using input box variable

I'm just trying to start with JavaScript and have put this little loop together. Providing I put 1 in the start box.. it works fine. If I put anything else though the loop itself never takes place.
According to the console my variables should all match the criteria for the loop to activate so I don't see the problem
function myFunction() {
console.clear();
var Start = document.getElementById("Start").value
console.log("Start=", Start)
var End = document.getElementById("End").value
console.log("End=", End)
var which_one = document.getElementById("which_one").value
console.log("which_one=", which_one)
var i = Start;
console.log("i=", i);
var Counter_Array = "";
console.log("Counter Array =", Counter_Array);
var Counter_Array_Split = "";
console.log("Counter Array Split = ", Counter_Array_Split)
var Show_Me = "";
console.log("Show Me = ", Show_Me)
console.log("------Loop Starts------")
for (; Start < End; Start++) {
console.log("Start=", Start)
console.log("i looped=", Start);
Counter_Array += "," + Start
var Counter_Array_Split = Counter_Array.split(',');
console.log("CounterArrayLog=", Counter_Array);
console.log("Counter Array Split = ", Counter_Array_Split);
// sets all elements with the id demo to have the value of the newURL variable
document.getElementById("array").innerHTML = Counter_Array_Split;
}
console.log("------Loop Ends------")
var Show_Me = Counter_Array_Split[which_one]
console.log("Show Me = ", Show_Me)
document.getElementById("my_val").innerHTML = Show_Me;
}
.My_Form {
display: block;
background-color: orange;
;
border: 1;
width: 500px;
border-style: solid;
border-radius: 5px;
}
.my_div {
display: block;
background-color: lightblue;
;
border: 1;
width: 500px;
border-style: solid;
border-radius: 5px;
}
<h2>Example Javascript Loop</h2>
<div class="My_Form">
Start #: <input type="text" name="Start" id="Start" value="2"><br> End #: <input type="text" name="fname" id="End" value="10"> <br> Show
me the <input type="text" name="fname" id="which_one" value="5">th value in the array <br>
</div>
<br>
<div class="my_div">
The array built was
<p id="array"></p>
The Value picked was
<p id="my_val"></p>
</div><br>
<button onclick="myFunction()">
Click Me
</button>
<br>
You need to use integers in the for loop, by default you use string, so you need to parse it first.
1st problem: '5' < '10' this is false.
2nd problem: '5'++ will convert it to 5 and only after that will be incremented.
function myFunction() {
console.clear();
var Start = parseInt( document.getElementById("Start").value, 10)
console.log("Start=", Start)
var End = parseInt(document.getElementById("End").value, 10)
console.log("End=", End)
var which_one = document.getElementById("which_one").value
console.log("which_one=", which_one)
var i = Start;
console.log("i=", i);
var Counter_Array = "";
console.log("Counter Array =", Counter_Array);
var Counter_Array_Split = "";
console.log("Counter Array Split = ", Counter_Array_Split)
var Show_Me = "";
console.log("Show Me = ", Show_Me)
console.log("------Loop Starts------")
for (; Start < End; Start++) {
console.log("Start=", Start)
console.log("i looped=", Start);
Counter_Array += "," + Start
var Counter_Array_Split = Counter_Array.split(',');
console.log("CounterArrayLog=", Counter_Array);
console.log("Counter Array Split = ", Counter_Array_Split);
// sets all elements with the id demo to have the value of the newURL variable
document.getElementById("array").innerHTML = Counter_Array_Split;
}
console.log("------Loop Ends------")
var Show_Me = Counter_Array_Split[which_one]
console.log("Show Me = ", Show_Me)
document.getElementById("my_val").innerHTML = Show_Me;
}
.My_Form {
display: block;
background-color: orange;
;
border: 1;
width: 500px;
border-style: solid;
border-radius: 5px;
}
.my_div {
display: block;
background-color: lightblue;
;
border: 1;
width: 500px;
border-style: solid;
border-radius: 5px;
}
<h2>Example Javascript Loop</h2>
<div class="My_Form">
Start #: <input type="text" name="Start" id="Start" value="2"><br> End #: <input type="text" name="fname" id="End" value="10"> <br> Show
me the <input type="text" name="fname" id="which_one" value="5">th value in the array <br>
</div>
<br>
<div class="my_div">
The array built was
<p id="array"></p>
The Value picked was
<p id="my_val"></p>
</div><br>
<button onclick="myFunction()">
Click Me
</button>
<br>

JavaScript firstChild.nodeValue not working

in my class we are using firstChild.nodeValue to display text if a user enters in an incorrect value. However, I can't get my two other fields to display the error message and only the first one. What am I doing wrong? When I run it in the code snipped is says that the nodeValue is null. I have the error messages display through a span and they are being used by the firstChild.nodeValue.
var $ = function (id) {
return document.getElementById(id);
}
var calculateClick = function () {
var investment = parseInt( $("investment").value);
var rate = parseFloat( $("rate").value);
var years = parseInt($("years").value);
//var amount = interest * rate * years;
if (investment==="" || investment < 100 || investment > 100000){
$("investment_error").firstChild.nodeValue="Must be an integer from 100 - 100,000";
}
else if (rate ==="" || rate <0.1 || rate >12){
$("rate_error").firstChild.nodeValue="Must be a value from .1 - 12";
}
else if (years ==="" || years <1 || years > 50){
$("years_error").firstChild.nodeValue="Must be an integer from 1 - 50";
}
var nt = 4*years;
var amount = investment * (1 + (rate/4)) ** nt;
$("future_value").value=amount.toFixed(2);
}
var clear_fields = function (){
$("investment").value="";
$("rate").value="";
$("years").value="";
$("future_value").value="";
}
window.onload = function () {
$("calculate").onclick = calculateClick;
$("calculate").ondblclick=clear_fields;
$("investment").focus();
}
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 48%;
padding: 0 1em .5em;
border: 3px solid blue;
}
h1 {
margin: .5em 0;
text-align: center;
}
label {
float: left;
width: 10em;
text-align: right;
padding-bottom: .5em;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
span {
color: blue;
}
<!DOCTYPE html>
<html>
<head>
<title>Future Value Calculator</title>
<link rel="stylesheet" href="future_value.css">
<script src="future_value.js"></script>
</head>
<body>
<main>
<h1 id="heading">Future Value Calculator</h1>
<label for="investment">Investment Amount:</label>
<input type="text" id="investment">
<span id="investment_error"> </span><br>
<label for="rate">Annual Interest Rate:</label>
<input type="text" id="rate">
<span id="rate_error"></span><br>
<label for="years">Number of Years:</label>
<input type="text" id="years">
<span id="years_error"></span><br>
<label for="future_value">Future Value:</label>
<input type="text" id="future_value" disabled="disabled"><br>
<label> </label>
<input type="button" id="calculate" value="Calculate"><br>
</main>
</body>
</html>
Its working on the first span becouse you have space between the span tags as:
with space
<span id="investment_error"> </span>
without
<span id="rate_error"></span>
In any case you should use innerHTML instead.
first child is good in case you already have a child in the html tags like this
<div>
<p id="i_am_div_first_child"> first child</p>
</div>
please hit correct answer if that was helpfull.
So what is the difference? A simple test will show you why.
console.log("1:", document.querySelector("#s1").firstChild)
console.log("2:", document.querySelector("#s2").firstChild)
<span id="s1"> </span>
<span id="s2"></span>
The one has a whitespace in it, the others do not the one with the whitespace has a firstChild, the others do not.
What should you do?
I would just set the textContent or innerHTML of the span and not set the nodeValue.
And another issue with your code, is you have
var rate = parseFloat( $("rate").value);
and
if ( rate==="")
That empty string check is not going to happen to be true ever since parseFloat is going to return NaN.
$("rate_error").firstChild returns null because it has no childrne (not even whit space), and so does not have a nodeValue property.
You could just use innerHTML instead of firstChild.nodeValue.
Also you don't need the else, just tell the user immediately all they have to fix.
var $ = function(id) {
return document.getElementById(id);
}
var calculateClick = function() {
var investment = parseInt($("investment").value);
var rate = parseFloat($("rate").value);
var years = parseInt($("years").value);
//var amount = interest * rate * years;
if (investment === "" || investment < 100 || investment > 100000) {
$("investment_error").innerHTML = "Must be an integer from 100 - 100,000";
}
if (rate === "" || rate < 0.1 || rate > 12) {
$("rate_error").innerHTML = "Must be a value from .1 - 12";
}
if (years === "" || years < 1 || years > 50) {
$("years_error").innerHTML = "Must be an integer from 1 - 50";
}
var nt = 4 * years;
var amount = investment * (1 + (rate / 4)) ** nt;
$("future_value").value = amount.toFixed(2);
}
var clear_fields = function() {
$("investment").value = "";
$("rate").value = "";
$("years").value = "";
$("future_value").value = "";
}
window.onload = function() {
$("calculate").onclick = calculateClick;
$("calculate").ondblclick = clear_fields;
$("investment").focus();
}
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 48 %;
padding: 0 1em .5em;
border: 3px solid blue;
}
h1 {
margin: .5em 0;
text-align: center;
}
label {
float: left;
width: 10em;
text-align: right;
padding-bottom: .5em;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
span {
color: blue;
}
<!DOCTYPE html>
<html>
<head>
<title>Future Value Calculator</title>
<link rel="stylesheet" href="future_value.css">
<script src="future_value.js"></script>
</head>
<body>
<main>
<h1 id="heading">Future Value Calculator</h1>
<label for="investment">Investment Amount:</label>
<input type="text" id="investment">
<span id="investment_error"> </span><br>
<label for="rate">Annual Interest Rate:</label>
<input type="text" id="rate">
<span id="rate_error"></span><br>
<label for="years">Number of Years:</label>
<input type="text" id="years">
<span id="years_error"></span><br>
<label for="future_value">Future Value:</label>
<input type="text" id="future_value" disabled="disabled"><br>
<label> </label>
<input type="button" id="calculate" value="Calculate"><br>
</main>
</body>
</html>

Add Dynamic Textbox if Radio Button is selected + Alert bug

I have 2 problems that i am not able to solve:
The code should show me a Alert if everything is correctly saved. I made that alert message, but if i add 10 elements and click save, i get 10 alerts.
Unable to add dynamical textfield after i press the Radio Button in the drop down. I did a lot of things, but whenever i implant it, indexedDB stops working.
Bonus question if somebody knows the answer to:
3. How can i save the Forms i made in the Forms tab, so i can search them later and put new info in?
var db;
function indexedDBOk() {
return "indexedDB" in window;
}
document.addEventListener("DOMContentLoaded", function() {
//No support? Go in the corner and pout.
if(!indexedDBOk) return;
var openRequest = indexedDB.open("idarticle_people4",1);
openRequest.onupgradeneeded = function(e) {
var thisDB = e.target.result;
if(!thisDB.objectStoreNames.contains("people")) {
thisDB.createObjectStore("people", {autoIncrement:true});
}
};
openRequest.onsuccess = function(e) {
db = e.target.result;
//Listen for add clicks
document.querySelector("#addButton").addEventListener("click", addPerson, false);
openRequest.onsuccess = function(e) {
alert('success: version 1 opened');
};
//Listen for get clicks
document.querySelector("#getButton").addEventListener("click", getPerson, false);
};
openRequest.onerror = function(e) {
}
},false);
function addPerson(e) {
//console.log(i);
var person= new Array(polje2);
for (n=0; n<i; n++) {
person.length=i;
var element='#element';
element+=n;
var unos='#unos';
unos+=n;
var provjera = document.querySelector(element).type;
var polje1 = document.querySelector(unos).innerHTML;
if (provjera=='checkbox') {
var polje2 = document.querySelector(element).checked
}
else {
polje2 = document.querySelector(element).value
}
if (polje2==='') {
alert ('Uspješno snimljeno');
}
//default for OS list is all, default for type is read
var transaction = db.transaction(["people"],"readwrite");
//Ask for the objectStore
var store = transaction.objectStore("people");
person[n]=
{pitanje: polje1, odgovor:polje2 };
}
//Perform the add
var request = store.add(person);
request.onerror = function(e) {
console.log("Error",e.target.error.
name);
//some type of error handler
};
request.onsuccess = function(e) {
console.log("Jej, uspjelo je");
}
}
function getPerson(e) {
var key = document.querySelector("#key").value;
if(key === "") return;
var transaction = db.transaction(["people"],"readonly");
var store = transaction.objectStore("people");
var request = store.get(Number(key));
request.onsuccess = function(e) {
var result = e.target.result;
if(result) {
var s = "<h2>Forma broj: "+key+"</h2><p>";
for(var j=0; j<result.length; j++) {
s+= (result[j].pitanje + ': ' + result[j].odgovor + "<br/>");
}
document.querySelector("#status").innerHTML = s;
}
else {
document.getElementById('element').style.visibility='visible'
}
}
}
// get allPeople
// Funkcija za pravljenje Elemenata
var i = 0;
var a = 1;
function mojaFunkcija() {
var type1 = document.getElementById('type1').value;
var type2 = document.getElementById('type2').value;
var question = document.getElementById('question').value;
var counter = 'Element';
counter+= a;
var prviElement=document.createElement('span');
prviElement.textContent= counter + ':' +' ';
document.body.appendChild(prviElement);
var pitanje= document.createElement('span');
var unos='unos';
unos += i;
pitanje.id=unos;
pitanje.textContent=question + ' ';
document.body.appendChild(pitanje);
var tip1 = document.createElement("input");
var element='element';
element += i;
tip1.id=element;
if (type1=='textbox') {
tip1.type=type2
} else {
tip1.type=type1
}
document.body.appendChild(tip1);
var linija1= document.createElement("br");
document.body.appendChild(linija1);
var linija2= document.createElement("br");
document.body.appendChild(linija2);
i++;
a++;
}
function AddTextBox(elm) {
var v = elm.value;
var iCounter = elm.id.replace('type1', '');
if (v == 'radio') {
var textbox = document.createElement('input');
textbox.type = 'text';
textbox.id = 'txtSecond' + iCounter;
elm.parentNode.insertBefore(textbox, elm.nextSibling);
} else {
//Ovaj kod ce da izbrise Textbox u slucaju da se izabere druga opcija.
var rmv = document.getElementById('txtSecond' + iCounter);
if (rmv != undefined) {
rmv.remove();
}
}
}
function modify_value()
{
var hidden_field = document.getElementById('test3');
hidden_field.value = 'testvalue';
}
/* Dropdown Button */
.dropbtn {
background-color: #A9A9A9;
color: white;
padding: 10px;
font-size: 16px;
text-align:center;
border: none;
cursor: pointer;
}
/* Dropdown button on hover & focus */
.dropbtn:hover, .dropbtn:focus {
background-color: #696969;}
input{
text-align:left;
}
.hide {
visibility: hidden
}
.h1 {
font-size: 4em;
}
.h2 {
font-size: 2.5em;
}
/* Dropdown Button */
.dropbtn2 {
background-color: #A9A9A9;
color: white;
padding: 10px;
font-size: 16px;
text-align:center;
border: none;
cursor: pointer;
margin-left:580px;
}
/* Dropdown button on hover & focus */
.dropbtn2:hover, .dropbtn2:focus {
background-color: #696969;}
input{
text-align:left;
}
.kocka {
max-width: 291px;
max-height: 94px;
background-color: #91ceff;
border: 20px;
border-style:solid;
border-color:#91ceff;
}
.kocka2 {
max-width: 291px;
max-height: 94px;
background-color: #91ceff;
border: 20px;
border-style:solid;
border-color:#91ceff;
}
/* Dropdown button on hover & focus */
.kocka2:hover, .kocka2:focus {
background-color: #696969;}
input{
text-align:left;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="pepo.css">
<meta charset="UTF-8">
<script src="basa.js"></script>
<title>OnlineForms</title>
</head>
<body>
<!--Ovaj kod je za Main Page-->
<Main class="kocka">
<div align="left">
<input type="button" class="dropbtn" value="Administration" onClick="window.location.reload();return false;"/>
      
<button class="dropbtn" id="getAllButton">Forms</button>
</div>
<br>
<div align="left">
<input type="number" id="key" class="dropbtn" Placeholder="Type the key value"/>
<button class="dropbtn" id="getButton"> Search </button>
<br>
<br>
</div>
</Main>
<!--Ovaj kod je za Elemente-->
<div id="element" class="hide">
<h1>Element <input type="text" class="dropbtn" id="question" value="" Placeholder="Type your question here"/>
<select title="ddmenu" class="dropbtn" id="type1">
<option selected disabled hidden value="Please select">Please select</option>
<option value="textbox">textbox</option>
<option value="checkbox">checkbox</option>
<option value="radio">radio button</option>
</select>
<select title="ddmenu" class="dropbtn" id="type2">
<option selected disabled hidden value="Please select">Please select</option>
<option value="none">none</option>
<option value="mandatory">mandatory</option>
<option value="number">numeric</option>
</select>
</h1>
<input type="button" id="adddugme" class="dropbtn2" value="Add" onclick="mojaFunkcija()"/>
<br>
<br>
<button id="addButton" class='dropbtn'>Save</button>
</div>
<br>
<br>
<div id="status"></div>
<br>
<div id="status2"></div>
</body>
</html>

Categories

Resources