Storing variable from calculated inputs - javascript - javascript

Welcome ! I have a question. Is the any possibility to store calculated data from three inputs for further math calculations? My clue is to store this dowform.value after calculations in new variable so i could for example divide this calculated value or multiply it and get new value. Code below for better understanding:
Javascript:
function dryOperatingWeight() {
const bew = document.getElementById("bew").value;
const crew = document.getElementById("crew").value;
const pantryDiv = document.getElementById("pantry").value;
let arr = document.getElementsByName("dow");
let tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value)) tot += parseInt(arr[i].value);
}
dowform.value = tot;
}
HTML:
<div class="form-group">
<label for="bew">Basic Empty Weight</label>
<input class="form-control" name="dow" type="text" id="bew" value="" onkeyup = "dryOperatingWeight()"/>
</div>
<div class="form-group">
<label id="crew"> Crew Weight</label>
<input
type="number"
name="dow"
class="form-control"
id="crew"
value=""
placeholder="crew weight"
onkeyup = "dryOperatingWeight()"
/>
<div class="form-group">
<label id="pantry">Pantry Weight</label>
<input
type="number"
name="dow"
class="form-control"
id="pantry"
placeholder="Enter pantry code"
onkeyup = "dryOperatingWeight()"
/>
</div>
<div class="form-group">
<label id="pantry">Water Weight</label>
<input
type="number"
name="dow"
class="form-control"
id="water"
placeholder="Enter water weight"
onkeyup = "dryOperatingWeight()"
/>
</div>
<div id="dow">
<div class="form-group">
<label for="dryoperating weight">Dry Operating Weight</label>
<input class="form-control" type="number" id="dowform" readonly/>
</div>
</div>

You can declare your variable outside of the function and just reuse it and modify it as needed.
let dow;
function dryOperatingWeight() {
const bew = document.getElementById("bew").value;
const crew = document.getElementById("crew").value;
const pantryDiv = document.getElementById("pantry").value;
let arr = document.getElementsByName("dow");
dow = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value)) dow += parseInt(arr[i].value);
}
dowform.value = dow;
}

Related

Get Javascript maxLength in input

I have a problem with downloading and displaying the value, when set to "rigidly" maxLenght - everything works fine, but when I want the script to download the value myself, I have a problem.
The script is supposed to get the value maxlenght = "" from each <input> and after typing by the user it will print out how many characters are left.
var maxLen = document.getElementsByClassName("handlerWorld").maxLength;
function countChar(jqObj) {
var len = jqObj.val().length;
var diff = maxLen - len;
if (len > maxLen) {
len = maxLen;
diff = 0;
}
jqObj.val(jqObj.val().substr(0, len)).prev('label').find('span.chars-twenty').text(diff);
}
$(document).ready(function () {
$("[class*='handlerWorld']").keyup(function () {
countChar($(this));
}).each(function () {
countChar($(this));
});
});
My HTML:
<div class="form-group">
<label for="nameIput">Nazwa firmy <span>Remaining: <span class="chars-twenty"></span></label>
<input type="text" id="name" maxlength="140" name="name" class="form-control handlerWorld">
</div>
<div class="form-group">
<label for="urlInput">URL <span>Remaining: <span class="chars-twenty"></span></label>
<input type="text" id="url" name="url" maxlength="100" class="form-control handlerWorld">
</div>
Edit:
Now I would like it to show the number of characters, e.g .:
10/140
quantity written / quantity in the value "maxlenght"
$("#add-category").find('span.maxchar').text(maxLen);
They work but not as they should.
Move the MaxLength calculation to the Count method
var maxLen = jqObj.attr("maxlength");
here's fiddle for you:
https://jsfiddle.net/d53yjpr8/1/
function countChar(jqObj) {
var maxLen = jqObj.attr("maxlength");
var len = jqObj.val().length;
var diff = maxLen - len;
if (len > maxLen) {
len = maxLen;
diff = 0;
}
jqObj.val(jqObj.val().substr(0, len)).prev('label').find('span.chars-twenty').text(diff);
}
$(document).ready(function() {
$("[class*='handlerWorld']").keyup(function() {
countChar($(this));
}).each(function() {
countChar($(this));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label for="nameIput">Test <span>Remaining:</span> <span class="chars-twenty"></span></label>
<input type="text" id="name" maxlength="140" name="name" class="form-control handlerWorld">
</div>
<div class="form-group">
<label for="urlInput">URL <span>Remaining:</span> <span class="chars-twenty"></span></label>
<input type="text" id="url" name="url" maxlength="100" class="form-control handlerWorld">
</div>

enabling submit btn after filling form (all inputs) with javascript no jquery

I am trying to create a form that the submit btn is disabled untill all (except for one) of the fields are filled.
this is the html:
<section id="contacSection">
<form id="contactForm">
<fieldset id="contactSection">
<legend>Your contact information</legend>
<label for="FirstName">First Name</label>
<input type="text" id="FirstName" name="FirstName" placeholder="First Name" required>
<label for="LastName">Last Name</label>
<input type="text" id="LastName" name="LastName" placeholder="Last Name">
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#gmail.com" required>
<label for="comments">Comment</label>
<textarea type="text" id="comments" name="comments" placeholder="Don't be shy, drop a comment here!" required></textarea>
</fieldset>
<fieldset>
<legend>Would you like to meet for?</legend>
<div class="radiobtn">
<input type="radio" id="meetingtype1" name=meetingtype value="coffee" checked> A coffee</input>
<input type="radio" id="meetingtype2" name=meetingtype value="zoom"> A zoom meeting</input>
<input type="radio" id="meetingtype3" name=meetingtype value="drive"> A drive to Eilat</input>
<input type="radio" id="meetingtype4" name=meetingtype value="chef"> A chef meal</input>
</div>
</fieldset>
<button id="submitform" type="submit" >Submit</button>
</form>
</section>
this is the js:
const firstName = document.querySelector('#FirstName');
const lastName = document.querySelector('#LastName');
const email = document.querySelector('#email');
const comments = document.querySelector('#comments');
const submitform = document.querySelector('#submitform');
const contactForm = document.querySelector('#contactForm');
submitform.disabled = true;
contactForm.addEventListener('keyup', function (){
var ins = document.getElementsByTagName("INPUT");
var txs = document.getElementsByTagName("TEXTAREA");
var filled = true;
for(var i = 0; i < txs.length; i++){
if(txs[i].value === "")
filled = false;
}
for(var j = 0; j < ins.length; j++){
if(ins[j].value === "")
filled = false;
}
submitform.disabled = filled;
});
first, it takes a few seconds until the btn becomes disabled. secondly, after I fill any field the btn becomes enabled.
thank you!
Disregarding the comments and the radio buttons and focusing on the main issue, try changing the second half of the code to:
submitform.disabled = true;
contactForm.addEventListener('keyup', function() {
var ins = document.getElementsByTagName("INPUT");
filled = []
for (var j = 0; j < ins.length; j++) {
if (ins[j].value === "")
filled.push(false);
else {
filled.push(true)
}
}
if (filled.includes(false) === false) {
submitform.disabled = false
};
});
and see if it works.
The reason it becomes enabled when you input something is because you are setting
submitform.disabled = filled
At the start, filled is set to true which is why the button is disabled. However, once you type something in any input, you set filled to false which enables the button (submitform.disabled = false).
There's a lot of ways to go about this but here's one. It increments a counter when ever something is filled in. Then you check if that counter is the same as the amount of inputs and textareas.
Secondly, we set the button to be disabled at the very start so even if you remove text from an input, the button will be disabled again if it wasn't
const firstName = document.querySelector('#FirstName');
const lastName = document.querySelector('#LastName');
const email = document.querySelector('#email');
const comments = document.querySelector('#comments');
const submitform = document.querySelector('#submitform');
const contactForm = document.querySelector('#contactForm');
submitform.disabled = true;
contactForm.addEventListener('keyup', function (){
var ins = document.getElementsByTagName("INPUT");
var txs = document.getElementsByTagName("TEXTAREA");
var amountFilled = 0
submitform.disabled = true
for(var i = 0; i < txs.length; i++){
if(txs[i].value !== "") {
amountFilled += 1
}
}
for(var j = 0; j < ins.length; j++){
if(ins[j].value !== "") {
amountFilled += 1
}
}
if (amountFilled === ins.length + txs.length) {
submitform.disabled = false
}
});
<section id="contacSection">
<form id="contactForm">
<fieldset id="contactSection">
<legend>Your contact information</legend>
<label for="FirstName">First Name</label>
<input type="text" id="FirstName" name="FirstName" placeholder="First Name" required>
<label for="LastName">Last Name</label>
<input type="text" id="LastName" name="LastName" placeholder="Last Name">
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#gmail.com" required>
<label for="comments">Comment</label>
<textarea type="text" id="comments" name="comments" placeholder="Don't be shy, drop a comment here!" required></textarea>
</fieldset>
<fieldset>
<legend>Would you like to meet for?</legend>
<div class="radiobtn">
<input type="radio" id="meetingtype1" name=meetingtype value="coffee" checked> A coffee</input>
<input type="radio" id="meetingtype2" name=meetingtype value="zoom"> A zoom meeting</input>
<input type="radio" id="meetingtype3" name=meetingtype value="drive"> A drive to Eilat</input>
<input type="radio" id="meetingtype4" name=meetingtype value="chef"> A chef meal</input>
</div>
</fieldset>
<button id="submitform" type="submit" >Submit</button>
</form>
</section>

Calculating multiple inputs value with javascript

i'm having trouble going trough making a calculator (sum only) of 5 inputs fields in html/javascript and i can't manage to find what's wrong in my code
i tried messing around with types such as int instead of var and passing the value into parseInt, i somehow managed to have a result like "11111" where it should be like "5" but alongside that case the result is never printed in the innerHTML even after i added the "if not null" condition
Here is my html
<body>
<h1 class="head-title"></h1>
<div class="input-group">
<label for="design">Design :</label>
<input class="input-text" type="number" id="design">
</div>
<div class="input-group">
<label for="plot">Plot :</label>
<input class="input-text" type="number" id="plot">
</div>
<div class="input-group">
<label for="character">Character :</label>
<input class="input-text" type="number" id="character">
</div>
<div class="input-group">
<label for="enjoyment">Enjoyment :</label>
<input class="input-text" type="number" id="enjoyment">
</div>
<div class="input-group">
<label for="music">Music :</label>
<input class="input-text" type="number" id="music">
</div>
<div class="button-group">
<button class="button-primary" onclick="ratingCompute();">Calculate</button>
</div>
<div class="input-group">
<label for="total">Rating :</label>
<p class="rating-score" id="total"></p>
</div>
</body>
and here is my javascript
function ratingCompute()
{
var designValue = document.getElementById("design").value;
var plotValue = document.getElementById("plot").value;
var charValue = document.getElementById("character").value;
var enjoyValue = document.getElementById("enjoyment").value;
var musicValue = document.getElementById("music").value;
var totalValue = designValue + plotValue + charValue + enjoyValue + musicValue;
if (totalValue != null)
{
document.getElementById("total").innerHTML = totalValue + "/10";
}
else
{
document.getElementById("total").innerHTML = "0/10";
}
}
Any clue?
JavaScript is not a type variable language try using let or const. And here is how you properly parse it. If you did it already then its because of your variable declaration.
let designValue = parseInt(document.getElementById("design").value);
let plotValue = parseInt(document.getElementById("plot").value);
let charValue = parseInt(document.getElementById("character").value);
let enjoyValue = parseInt(document.getElementById("enjoyment").value);
let musicValue = parseInt(document.getElementById("music").value);
In javascript you should use keyword var/let/const instead of int. and you have to convert String type input value to int using parseInt method.
Please check this:
function ratingCompute()
{
var designValue = parseInt(document.getElementById("design").value);
var plotValue = parseInt(document.getElementById("plot").value);
var charValue = parseInt(document.getElementById("character").value);
var enjoyValue = parseInt(document.getElementById("enjoyment").value);
var musicValue = parseInt(document.getElementById("music").value);
var totalValue = designValue + plotValue + charValue + enjoyValue + musicValue;
if (totalValue)
{
document.getElementById("total").innerHTML = totalValue + "/10";
}
else
{
document.getElementById("total").innerHTML = "0/10";
}
}
<body>
<h1 class="head-title"></h1>
<div class="input-group">
<label for="design">Design :</label>
<input class="input-text" type="number" id="design">
</div>
<div class="input-group">
<label for="plot">Plot :</label>
<input class="input-text" type="number" id="plot">
</div>
<div class="input-group">
<label for="character">Character :</label>
<input class="input-text" type="number" id="character">
</div>
<div class="input-group">
<label for="enjoyment">Enjoyment :</label>
<input class="input-text" type="number" id="enjoyment">
</div>
<div class="input-group">
<label for="music">Music :</label>
<input class="input-text" type="number" id="music">
</div>
<div class="button-group">
<button class="button-primary" onclick="ratingCompute()">Calculate</button>
</div>
<div class="input-group">
<label for="total">Rating :</label>
<p class="rating-score" id="total"></p>
</div>
</body>
As mentioned by #Joshua Aclan, JavaScript does not have an "int" variable declaration, only "var". Also you have to cast all of the inputs to int or float, because otherwise you are adding strings and the values of input fields are always strings. Also the output is most likely empty because int designValue... produces an error.
function ratingCompute()
{
var designValue = parseInt(document.getElementById("design").value);
var plotValue = parseInt(document.getElementById("plot").value);
var charValue = parseInt(document.getElementById("character").value);
var enjoyValue = parseInt(document.getElementById("enjoyment").value);
var musicValue = parseInt(document.getElementById("music").value);
var totalValue = designValue + plotValue + charValue + enjoyValue + musicValue;
if (totalValue != null)
{
document.getElementById("total").innerHTML = totalValue + "/10";
}
else
{
document.getElementById("total").innerHTML = "0/10";
}
}

Output wont show (javascript)

I have 1 input. And it has to print out 2 outputs 1 with -1 to the output and the other with -2. But the output doesn't show anything. can someone tell me what I'm doing wrong here.
Code:
// Meters en Centimeters value
function updateTotal() {
const list = document.getElementsByClassName("AutosubmitCalculator");
const values = [];
for (let i = 0; i < list.length; ++i) {
values.push(parseFloat(list[i].value));
}
let total = values.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
});
document.getElementById("schermentotaal").value = total - 2;
document.getElementById("schermentotaal2").value = total - 1;
}
HTML Input:
<div class="InputField InputMeters">
<input type="tel" name="iFenceMeters" id="FenceMeters" class="AutosubmitCalculator" data-minimum-length="1" tabindex="1" placeholder="00" maxlength="3" value="">
<div class="FormExclamation Tipped Hidden" id="FormCalculatorExclamationFence">0</div>
</div>
HTML Output:
<div class="SummaryRow">
<strong>Schermen</strong>
<input name="schermentotaal" type="text" id="schermentotaal" value=""></input>
</div>
<div class="SummaryRow">
<strong>Palen en onderplaten</strong>
<input name="schermentotaal2" type="text" id="schermentotaal2" value=""></input>
</div>
Thanks in advance :D
You're not calling your updateTotal anywhere. I suggest you run this function on the oninput event on your input field. This will make it so that whenever you enter a number it will run the function updateTotal.
You also have some additional errors, such as you are trying to get the element with the id total but don't have an element with this id in your HTML.
document.getElementById("total").value
I've changed this to be schermentotaal2 which is a valid id in your HTML:
document.getElementById("schermentotaal2").value
See working example below:
function updateTotal() {
const list = document.getElementsByClassName("AutosubmitCalculator");
const values = [];
for (let i = 0; i < list.length; i++) {
values.push(parseFloat(list[i].value));
}
let total = values.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
});
document.getElementById("schermentotaal").value = (total - 2) || '';
document.getElementById("schermentotaal2").value = (total - 1) || '';
}
<div class="InputField InputMeters">
<input type="tel" name="iFenceMeters" id="FenceMeters" class="AutosubmitCalculator" data-minimum-length="1" tabindex="1" placeholder="00" maxlength="3" value="" oninput="updateTotal()" />
<div class="FormExclamation Tipped Hidden" id="FormCalculatorExclamationFence">0</div>
</div>
<div class="SummaryRow">
<strong>Schermen</strong>
<input name="schermentotaal" type="text" id="schermentotaal" value="" />
</div>
<div class="SummaryRow">
<strong>Palen en onderplaten</strong>
<input name="schermentotaal2" type="text" id="schermentotaal2" value="" />
</div>
Also, if you only have one input you may want to reconsider using a class to get the input value for this as you don't require a loop to get the value from one input field.

A function that collects an array of numbers as a parameter and returns an array of percentages?

I'm currently a beginner and trying to understand how to basically use a function get an array of the numbers from each input to then figure out how to make an individual percentage for each candidate. In the JS, using that to get the total but is there a way to get each individual number from each input somehow? Maybe I'm going into a wrong direction with my for loop :/ Any direction or hints would be great.
<div>
<label for="votes1">Votes for Candidate 1</label>
<input type="number" name="votesPerPerson" id="cand1" placeholder="Vote count">
</div>
<div>
<label for="votes2">Votes for Candidate 2</label>
<input type="number" name="votesPerPerson" id="cand2" placeholder="Vote count">
</div>
<div>
<label for="votes3">Votes for Candidate 3</label>
<input type="number" name="votesPerPerson" id="cand3" placeholder="Vote count">
</div>
<output id="totalvotes"></output>
Here's the JS for it
function totalVotes() {
var votes = document.getElementsByName("votesPerPerson");
var totalVotes = 0;
for( var i = 0; i < votes.length; i ++ ) {
totalVotes += parseInt(votes[i].value);
}
document.getElementById("totalvotes").innerHTML = totalVotes;
}
Looks like you have a good grasp of getting the sum. To create an array, there's several ways you can do that but I recommend mapping it from the collection of elements like this:
function totalVotes() {
var votes = document.getElementsByName("votesPerPerson");
var total = document.getElementById("totalvotes");
// create new array
var percentages = [];
var totalVotes = 0;
// reset innerHTML in case loop returns early due to invalid value
total.innerHTML = "";
// reset each vote percentage
for (var i = 0; i < votes.length; i++) {
votes[i].nextElementSibling.innerHTML = "";
}
// overwrite each index with value
for (var i = 0; i < votes.length; i++) {
totalVotes += percentages[i] = parseInt(votes[i].value);
// one of the values is invalid
if (isNaN(percentages[i])) return;
}
total.innerHTML = totalVotes;
// calculate percentages here by mapping array of votes
for (var i = 0; i < percentages.length; i++) {
percentages[i] = 100 * percentages[i] / totalVotes;
votes[i].nextElementSibling.innerHTML = percentages[i].toFixed(2) + "%";
}
}
document.addEventListener('change', totalVotes)
<div>
<label for="votes1">Votes for Candidate 1</label>
<input type="number" name="votesPerPerson" id="cand1" placeholder="Vote count">
<output></output>
</div>
<div>
<label for="votes2">Votes for Candidate 2</label>
<input type="number" name="votesPerPerson" id="cand2" placeholder="Vote count">
<output></output>
</div>
<div>
<label for="votes3">Votes for Candidate 3</label>
<input type="number" name="votesPerPerson" id="cand3" placeholder="Vote count">
<output></output>
</div>
<output id="totalvotes"></output>
function totalVotes() {
var votes = document.getElementsByName("votesPerPerson");
var totalVotes = 0;
var percentages = [];
for( var i = 0; i < votes.length; i ++ ) {
totalVotes += parseInt(votes[i].value);
percentages[i] = parseInt(votes[i].value);
}
percentages = percentages.map(function(candidateVotes) {return candidateVotes/totalVotes;});
document.getElementById("totalvotes").innerHTML = totalVotes;
}
The percentages are in the array of the same name, then you can do whatever you want with it!
Hopes this helps!
You mostly have the idea. You just need to attach some event handlers (with one other minor change).
function totalVotes() {
var votes = document.getElementsByName("votesPerPerson");
var totalVotes = 0;
for(var i = 0; i < votes.length; i++) {
totalVotes += parseInt(votes[i].value || 0); // "Minor change" here
}
document.getElementById("totalvotes").innerHTML = totalVotes;
}
// Additions below this point
var votes = document.getElementsByName("votesPerPerson");
for( var i = 0; i < votes.length; i ++ ) {
votes[i].addEventListener('change', totalVotes);
}
totalVotes(); // Run once to get 0 to show without changing anything
<div>
<label for="votes1">Votes for Candidate 1</label>
<input type="number" name="votesPerPerson" id="cand1" placeholder="Vote count">
</div>
<div>
<label for="votes2">Votes for Candidate 2</label>
<input type="number" name="votesPerPerson" id="cand2" placeholder="Vote count">
</div>
<div>
<label for="votes3">Votes for Candidate 3</label>
<input type="number" name="votesPerPerson" id="cand3" placeholder="Vote count">
</div>
<output id="totalvotes"></output>
Now, that code works, but note some of the repetition, global variables, etc. Here's an alternative that may offer you some different ways of accomplishing the same things:
// If you want to know what this outer function is, look up "IIFE"
(function() {
'use strict';
// Get the elements (and make sure they are put in an array)
var voteInputEls = Array.from(
document.getElementsByName('votesPerPerson')
);
// This is used below to handle the change event
function setTotalVotes() {
// "reduce" the voteInputEls array to a total value
var totalVotes = voteInputEls.reduce(function (lastVal, voteInputEl) {
return lastVal + parseInt(voteInputEl.value || 0);
}, 0);
document.getElementById('totalvotes').innerHTML = totalVotes;
}
// Attach event listeners
voteInputEls.forEach(function(voteInputEl) {
voteInputEl.addEventListener('change', setTotalVotes);
});
setTotalVotes(); // Run once to get 0
})();
<div>
<label for="votes1">Votes for Candidate 1</label>
<input type="number" name="votesPerPerson" id="cand1" placeholder="Vote count">
</div>
<div>
<label for="votes2">Votes for Candidate 2</label>
<input type="number" name="votesPerPerson" id="cand2" placeholder="Vote count">
</div>
<div>
<label for="votes3">Votes for Candidate 3</label>
<input type="number" name="votesPerPerson" id="cand3" placeholder="Vote count">
</div>
<output id="totalvotes"></output>

Categories