How to get auto + javascript input fields - javascript

I'm trying to get an autosum from fields, the issue is that if the total of fields are without value the script is not working correctly, and also if there are more than 7 fields again the script is not working.
here is the javascript:
function getTotal()
{
var value01 = document.getElementById('value01').value;
var value02 = document.getElementById('value02').value;
var value03 = document.getElementById('value03').value;
var value04 = document.getElementById('value04').value;
var value05 = document.getElementById('value05').value;
var value06 = document.getElementById('value06').value;
var value07 = document.getElementById('value07').value;
// Add them together and display
var sum = parseInt(value01) + parseInt(value02) + parseInt(value03) + parseInt(value04) + parseInt(value05) + parseInt(value06) + parseInt(value07);
document.getElementById('sum_total').value = sum;
}
inputs:
<input type="text" id="value01" />
<input type="text" id="value02" />
<input type="text" id="value03" />
here is starting to be added with a button more input fields.
<input type="text" id="+" />
<input type="text" id="++" />
<input type="button" value="Add Them Together" onclick="getTotal();" />
my question is, how can i get an auto + on var value01 02 03 etc.
Any help is appreciated.

Your question is not very clear and so I'm not too sure what you are wanting to do so feel free to offer clarification for optimum assistance. On that note, based off of what you have provided, I have two things to point out:
1) Your ID of "+" is not valid. Per the HTML 4 spec:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be
followed by any number of letters, digits ([0-9]), hyphens ("-"),
underscores ("_"), colons (":"), and periods (".").
2) Instead of creating a different var containing each value, I would recommend creating a function that you can use within a for loop that will determine the sums of each incremental input. This is more DRY and helps simplify things if the number of inputs were to grow.
function getValues(id){
return document.getElementById(id).value;
}
The pure JavaScript solution below begins with one input box and will add additional inputs with the click of a button, which I believe is what you're looking for. You can modify the number of initial input boxes accordingly, but it should give you an idea.
Javascript:
var max = 1;
function getValues(id){
var result = document.getElementById(id).value;
return (result ? result : 0);
}
function addInput(){
max++;
var input = '<input type="text" id="value'+ max +'" />';
document.getElementById("valuesContainer").innerHTML += input;
}
function getTotal(){
var sum = 0;
for(var i=1; i <= max; i++){
sum = sum + parseFloat(getValues("value" + i));
}
document.getElementById("total").innerHTML = sum;
}
HTML:
<div id="valuesContainer">
<input type="text" id="value1" />
</div>
<input type="button" value="Add Value" id="addMore" onclick="addInput();" />
<input type="button" value="Calculate Total" onclick="getTotal();" />
<div id="total"></div>
Demo: http://jsfiddle.net/Y4xgU/

Related

Unsure why my math min function is not working but math max function is in script code

function selectHighestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMaxNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue").value;
valueSecondNumber = document.getElementById("txtSecondNumberValue").value;
valueThirdNumber = document.getElementById("txtThirdNumberValue").value;
selectMaxNumber = Math.max(valueFirstNumber, valueSecondNumber, valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML = selectMaxNumber;
}
function selectLowestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMinNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue").value;
valueSecondNumber = document.getElementById("txtSecondNumberValue").value;
valueThirdNumber = document.getElementById("txtThirdNumberValue").value;
selectMinNumber = Math.min(+valueFirstNumber, +valueSecondNumber, +valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML = selectMinNumber;
}
<main class="fancy-border">
<form id="userNumberEntry">
<p><label for="txtFirstNumberValue">Enter your first number here:</label>
<input type="text" id="txtFirstNumberValue" maxlength="20" size="20"></p>
<p><label for="txtSecondNumberValue">Enter your second number here:</label>
<input type="text" id="txtSecondNumberValue" maxlength="20" size="20"></p>
<p><label for="txtThirdNumberValue">Enter your third number here:</label>
<input type="text" id="txtThirdNumberValue" maxlength="20" size="20"></p>
<p><input type="button"
value="Find the highest number"
id="btnSubmit"
onclick="selectHighestNumber();">
</p>
<p><input type="button"
value="Find the lowest number"
id="btnSubmit"
onlick="selectLowestNumber();">
</p>
<br>
<div id="selectRankingNumbersResults">
</div> <!--end of selectRankingNumberValues div-->
</form>
</main>
So very recently I came into a problem in my script where I was unsure why my Math min function was not working. I asked about that issue in a previous question and found that a spelling error was causing one of my functions to not work. Essentially, I have two functions, a math min, and a math max, both serving similar purposes. I am working in Html code, and use a script for my functions within my Html document. The purpose of this math min and math max function is that I have three text boxes to input numbers into, there are two buttons that will either serve to show the highest or lowest of these three values. My math max function works fine and shows the highest value, however, my math min function does not. It does not return any value at all. I have cross-checked my code to see if it was misspelled, spacing errors, or other mismatched words with the rest of my code but none of it seems to be the problem. This is how my math max and math min functions in my script look respectively.
function selectHighestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMaxNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue")
.value;
valueSecondNumber = document.getElementById("txtSecondNumberValue")
.value;
valueThirdNumber = document.getElementById("txtThirdNumberValue")
.value;
selectMaxNumber = Math.max(valueFirstNumber, valueSecondNumber,
valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML =
selectMaxNumber;
}
function selectLowestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMinNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue")
.value;
valueSecondNumber = document.getElementById("txtSecondNumberValue")
.value;
valueThirdNumber = document.getElementById("txtThirdNumberValue")
.value;
selectMinNumber = Math.min(valueFirstNumber, valueSecondNumber,
valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML =
selectMinNumber;
}
If anyone could help me understand where I might be going wrong, that would be greatly appreciated! I am very confused about what I could have coded wrong, so any insight/outlook is greatly appreciated!
Math.max and Math.min will return the largest/smallest value (or -Infinity/Infinity if no values are supplied) and then convert to a number if they're not already, this means that strings will first be compared as strings and not numbers ("123" > "3"), so you should first convert each value to a number.
Also I recommend batching up the whole process instead of getting each element separately, reading its value, converting it to a number, checking it's valid, passing it to the function. So try to do the whole thing in a loop of some sort.
document.querySelector("form").addEventListener("submit", function(event) {
event.preventDefault();
console.log("Max:" + getEdgeCase(true));
console.log("Min:" + getEdgeCase(false));
});
function getEdgeCase(flag) {
// get all the inputs in one go and convert them to an array
var inputList = [].slice.call(document.querySelectorAll("form input[type=\"number\"]"));
var inputList = inputList.map(function(input) {
// convert to number, if it's not a valid number and ends up as NaN then return 0
return +input.value || 0;
});
// get the right function and call apply (spreads an array into arguments)
return Math[flag ? "max" : "min"].apply(Math, inputList);
}
<form>
<input type="number" />
<input type="number" />
<input type="number" />
<input type="submit" />
</form>

How can I pattern match ID only making sure the variable number matches without having to hardcode all of the possibilities?

I've recently become familiar with Jquery selectors....and they work great. Starts with...ends with....
The problem I have currently is that all of my variable names essentially start with similar patterns and end with similar patterns. This ID is generated from somewhere else so I'm hoping I can do something to use it effectively.
The pattern ID format essentially looks like...
"#id_newbudgetlineitem_set-0-line_item_october"
"#id_newbudgetlineitem_set-0-line_item_november"
"#id_newbudgetlineitem_set-0-line_item_december"
I want to essentially matching on the set-* but only if it's identical to the other ids in my array. Is this even possible without having to hard code anywhere from set-0 to set-1000? Unfortunately the class for each one is the same as is the name situation. Is there someway to say if the set numbers all match in a given array then add them up? I can't use starts with or ends with in this case...and don't want to hardcode 1000 possibilities. Thanks in advance for any ideas or thoughts.
I am trying to do something like.....
function update_total()
{
var total = 0;
$('.budget').each(function(index, element) {
"#id_newbudgetlineitem_set-0-line_item_october" +
"#id_newbudgetlineitem_set-0-line_item_november" +
"#id_newbudgetlineitem_set-0-line_item_december"
var val = parseFloat($(element).val());
if( !isNaN( val )){
total += val;
}
});
$("#id_total").val(total);
}
Here's a working solution........
function update_total_total_total()
{
var ret = +$("input[name$='set-0-line_item_january']").val() + +$("input[name$='set-0-line_item_february']").val() + +$("input[name$='set-0-line_item_march']").val() + +$("input[name$='set-0-line_item_april']").val() + +$("input[name$='set-0-line_item_may']").val() + +$("input[name$='set-0-line_item_june']").val() + +$("input[name$='set-0-line_item_july']").val() + +$("input[name$='set-0-line_item_august']").val() + +$("input[name$='set-0-line_item_september']").val() + +$("input[name$='set-0-line_item_october']").val() + +$("input[name$='set-0-line_item_november']").val() + +$("input[name$='set-0-line_item_december']").val();
$("input[name$='set-0-line_item_total']").val(ret);
}
But I could have up to 1000 different set values. Is there some other way to do this without having to hard code this 999 more times?
This is a lot closer....but total still says 0. It's updating all of the totals to 0...so that's progress but not getting the actual totals. Forward progress thanks to Swati.
function update_total_total_total() {
//get length of input line_total for each sets..
for (var i = 0; i < $("[name$=line_item_total]").length; i++) {
var total = 0;
//get all inputs but not line_item _total
$(`input[name*=id_newbudgetlineitem_set-${i}-line_item]:not([name$=line_item_total]):not([name$=line_item_cost_center]):not([name$=line_item_description])`).each(function(index, element) {
var val = parseFloat($(element).val());
if( !isNaN( val )){
total += val;
}
})
$(`input[id$=set-${i}-line_item_total]`).val(total); //set value..of input
}
}
You can get length of total input whose name ends with line_item_total so this value will be counter for for-loop.
Then , inside for loop you can use $(`input[name*=id_newbudgetlineitem_set-${i}-line_item]:not([name$=line_item_total])`) this will fetch values from all inputs expect the line_total_item then add value on each iteration .
Lastly , use $(`input[name$=set-${i}-line_item_total]`).val(total); to set total inside line_total_item textbox.
Demo Code :
function update_total_total_total() {
//get length of input line_total for each sets..
for (var i = 0; i < $("[name$=line_item_total]").length; i++) {
var total = 0;
//get all inputs but not line_item _total
$(`input[name*=id_newbudgetlineitem_set-${i}-line_item]:not([name$=line_item_total]):not([name$=line_item_cost_center]):not([name$=line_item_description])`).each(function(i, element) {
var val = parseFloat($(element).val());
if (!isNaN(val)) {
total += val;
}
})
$(`input[name$=set-${i}-line_item_total]`).val(total); //set value..of input
}
}
update_total_total_total()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
SET 0 :
<input type="text" name="id_newbudgetlineitem_set-0-line_item_october" value="5">
<input type="text" name="id_newbudgetlineitem_set-0-line_item_november" value="51">
<input type="text" name="id_newbudgetlineitem_set-0-line_item_december" value="15">
<br/> Total :
<input type="text" name="id_newbudgetlineitem_set-0-line_item_total" value="" placeholder="total">
<input type="text" name="id_newbudgetlineitem_set-0-line_item_cost_center">
<input type="text" name="id_newbudgetlineitem_set-0-line_item_description">
</div>
<br/>
<div>
SET 1
<input type="text" name="id_newbudgetlineitem_set-1-line_item_october" value="5">
<input type="text" name="id_newbudgetlineitem_set-1-line_item_december" value="534">
<br/> Total :
<input type="text" name="id_newbudgetlineitem_set-1-line_item_total" value="" placeholder="total">
<input type="text" name="id_newbudgetlineitem_set-1-line_item_cost_center">
<input type="text" name="id_newbudgetlineitem_set-1-line_item_description">
</div>
<br/>
<div>
SET 2
<input type="text" name="id_newbudgetlineitem_set-2-line_item_december" value="4">
<input type="text" name="id_newbudgetlineitem_set-2-line_item_oct" value="5">
<br/> Total :
<input type="text" name="id_newbudgetlineitem_set-2-line_item_total" value="" placeholder="total">
<input type="text" name="id_newbudgetlineitem_set-2-line_item_cost_center">
<input type="text" name="id_newbudgetlineitem_set-2-line_item_description">
</div>
This was the final working code. As Swati suggested it was an incorrect name reference.
function update_total_total_total() {
for (var i = 0; i < $("[name$=line_item_total]").length; i++) {
var total = 0;
$(`input[name*=newbudgetlineitem_set-${i}-line_item]:not([name$=line_item_total]):not([name$=line_item_cost_center]):not([name$=line_item_description])`).each(function(i, element) {
var val = parseFloat($(element).val());
if( !isNaN( val )){
total += val;
}
})
$(`input[name$=set-${i}-line_item_total]`).val(total);
}
}

Javascript Arrays. Adding, subtracting and totaling

I'm having a little trouble with an assignment a teacher dished out to my class involving javascript arrays. What they essentially want us to do is to create sort of cart / calculator hybrid that allows users to input numbers, store them and array and display those numbers on the webpage, then be able to either add them together for a total or reset them and start over.
I think I more or less know how to make a reset button, and I believe I've figured out how to add items to the array efficiently enough, but I'm kinda stumped on how to show those items on an html page and how to add them together to make and show a total. Any help would be appreciated, I'm kinda new at this and so far the instructions from our source material are a bit vague and hard to understand, at least for me!
So far I have some simple html for the input field and an "add number" button which will add the input field to the array (I will limit it to numbers only later and will).
<form onsubmit="return userNumber()">
<p>Number:</p>
<input type="text" id="box" />
<br>
<input type="button" value="Add Number" />
<input type="button" value="Calculate" />
<input type="button" value="Reset" />
</form>
I've no code yet for the Calculate or Reset button, but for the Add Number button which does seem to work properly when I bring up the console, I just need it to also display on the webpage. Here's what I have for that.
var numbers = [];
function userNumber() {
boxvalue = document.getElementById('box').value;
numbers.push(boxvalue);
console.log(numbers);
return false;
}
I've attached an image of what our teacher showed us, they want us to make it only similar in function, looks are not as important.
Once again, thank you to anyone who can assist, I'm very lost on where to go from here!
First, give them all an id. It's a lot easier to work with them when they all have the "names". And then you can easily handle the events (clicks in this example).
Notice, when you click on the "Add" button, before push you need to use parseInt(string, base) since input.value is a string, and + operator is concatenation for string, not addition. Like sum += numbers[i]; below.
And there is a couple of protection for corner cases when you click the "Calculate" button with an empty numbers array for example.
var numbers = [];
var boxInput = document.getElementById("box");
var addBtn = document.getElementById("add");
var calculateBtn = document.getElementById("calculate");
var resetBtn = document.getElementById("reset");
var allNumbers = document.getElementById("all-numbers");
var calculatedNumbers = document.getElementById("calculated-numbers");
addBtn.addEventListener("click", function() {
if (boxInput.value.length > 0) {
numbers.push(parseInt(boxInput.value, 10));
boxInput.value = "";
}
allNumbers.innerHTML = numbers.join(" ");
});
calculateBtn.addEventListener("click", function() {
if (numbers.length === 0) {
return;
}
for (var i = 0, sum = 0; i < numbers.length; i++) {
sum += numbers[i];
}
calculatedNumbers.innerHTML = numbers.join(" + ") + " = " + sum;
});
resetBtn.addEventListener("click", function() {
numbers = [];
boxInput.value = "";
allNumbers.innerHTML = "";
calculatedNumbers.innerHTML = "";
});
<p>
<label for="box">Number:</label>
<input id="box" type="number" />
</p>
<p>
<input type="button" id="add" value="Add Number" />
<input type="button" id="calculate" value="Calculate" />
<input type="button" id="reset" value="Reset" />
</p>
<h3>Numbers added:</h3>
<p id="all-numbers"></p>
<h3>Sums of numbers added:</h3>
<p id="calculated-numbers"></p>

Basic math functions in JavaScript to show on HTML page

I would like to make major of basic math functions (addition, subtraction, ect.) to develop in JavaScript. Input parameters should be from HTML webpage, than do the in JavaScript and return result on the same HTML page.
function math() {
//document.getElementById("frm1").innerHTML;
var numb = document.getElementById("number").innerHTML;
var mod = document.getElementById("modifier").innerHTML;
console.log(numb);
console.log(mod);
var sum = 1; //numb + mod; //the 1 is a placeholder
console.log(sum);
sum = document.getElementById("sum").innerHTML;
}
<form id="frm1" action="randScript.js">
Number: <input type="int" name="number" id="number"><br> Modifiers: <input type="int" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id="sum"></p>
Your form tag has an action attribute. This means the page will submit your information to the specified page. You can use jQuery to prevent the form from submitting.
$("#yourFormId").on("submit",function(event){event.preventDefault()})
You can also edit the forms action attribute itself to prevent it from submitting.
<form id="frm1" action"javascript:void(0);">
First: The type is text - there is no "int" thing
Number: <input type="text" name="number" id="number">
Second: if we read a bit documentation we figure also out how to get the alue into the JS part
var numb = document.getElementById("number").value;
here you can now do your further homework ;)
Third: Get things back:
either use another input. They work two ways.
document.getElementById("result").value="I did not do my homework alone"
or you place a div somewhere with an id
<div id="result"> </div>
and now you can really use innerHTML in js
document.getElementById("result").innerHTML="I am too lazy";
The rest and to put it all together is now up to you :) Have fun to study :)
Try that if you want to display the sum at the html element:
document.getElementById("sum").innerHTML = sum;
But a more precise Question would help!
There is no int type for form inputs in HTML you can learn here about input types: HTML form input types
<form id="frm1" >
Number1: <input type="number" name="number" id="number1"><br>
Number2: <input type="number" name="number" id="number2"><br>
Modifiers: <input type="text" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id = "sum"></p>
<script type="text/javascript">
function math() {
var numb1 = parseInt(document.getElementById("number1").value);
var numb2 = parseInt(document.getElementById("number2").value);
var mod = document.getElementById("modifier").value;
if(mod == '+'){
var sum = numb1 + numb2;
}else if(mod == '-'){
var sum = numb1 - numb2;
}else if(mod == '*'){
var sum = numb1 * numb2;
}
if(sum === undefined){
alert('invalid inputs');
return false;
}else{
document.getElementById("sum").innerHTML = sum;
}
return true;
}
To retrieve inputs values properly use value rather then innerHtml.
Retrieved values are strings so you need to parse them to numbers (with parseInt) before using them in math.
function math() {
const numb = document.getElementById("number").value;
const mod = document.getElementById("modifier").value;
sum = document.getElementById("sum").innerText = parseInt(numb) + parseInt(mod);
}

Limiting Text Input Based On Another Text Input

It seems pretty simple but I can't find a good way to do it.
I am doing a research bar which allow users to search something in terms of price mini and price maxi.
So :
I have two text input types (in html of course) "price_mini?" and "price_maxi?".
"Price_mini" cannot be bigger than "price_maxi".
How can I limit the users input of "price_mini" so that if does not allow the user to enter more than the "price_maxi" variable's input and then display an error on save(search) if the mini number is bigger than price_maxi.
Something like this should work, I couldn't get JSFiddle to handle the form to show you a good example and I don't do much in plain javascript now in days so pardon me if there is a small error or two.
HTML
<form name="myForm" onSubmit="submit()" method="post">
<input name="price_mini" type="text">
<input name="price_maxi" type="text">
<input type="submit" value="Submit">
</form>
Javascript
function submit(){
var price_mini = document.forms["myForm"]["price_mini"].value;
var price_maxi = document.forms["myForm"]["price_maxi"].value;
if(Number(price_mini) > Number(price_maxi)){
alert("Minimum price must be less than maximum price!");
}else{
// Your search code here
}
}
Imagine this html
<input id="min" type="text">
<input id="max" type="text">
This should be the correct javascript
var min = document.getElementById("min");
var max = document.getElementById("max");
min.change(function() {
if(Number(this.value) > Number(max.value)) {
this.value = max.value; // replace min with the same max value if it's bigger
}
}
Let's assume that this is your HTML.
<input id="min" type="text">
<input id="max" type="text">
The working JavaScript is this with the behavior if the max field is empty.
var min = document.querySelector('#min');
var max = document.querySelector('#max');
var calculate = function() {
if(max.value == '') return;
if(Number(min.value) > Number(max.value)) {
min.value = max.value;
}
}
min.addEventListener('input', calculate);
max.addEventListener('input', calculate);
You should compare them when they have value (min && max). If you notice that min is higher you can alert to the user or change it automatically to the lowest or to the highest.
$('.calc_input').change( function() {
var min = $('#min').val();
var max = $('#max').val();
if ( (min && max) && min > max ) {
alert('This can not be!');
// $('#min').val() = max;
// $('#max').val() = min;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Min:<input id="min" class="calc_input">
<br>
Max:<input id="max" class="calc_input">

Categories

Resources