validating the sum of inputs in text area - javascript

I have form that adds 6 user inputs. I want to have an alert if the total is not 100 or the user enters something other than a number. The alert works for a total greater than 100, but how do you check if it's less than 100 and all the inputs have been filled in? Right now I get the alert when the first input is being filled in.
<form name="myForm" id="form1">
<input oninput="findTotal()" type="text" name="qty" id="qty1" /> <br>
<input oninput="findTotal()" type="text" name="qty" id="qty2" /><br>
<input oninput="findTotal()" type="text" name="qty" id="qty3" /><br>
<input oninput="findTotal()" type="text" name="qty" id="qty4" /> <br>
<input oninput="findTotal()" type="text" name="qty" id="qty5" /><br>
<input oninput="findTotal()" type="text" name="qty" id="qty6" /><br>
<textarea type="text" name="total" id="total" min="100" max="100" readonly></textarea>
</form>
<script>
function findTotal(){
"use strict";
var arr = document.getElementsByName('qty');
var tot=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value)) {
tot += parseInt(arr[i].value);
}
}
document.getElementById('total').value = tot;
if (tot > 100) {
alert("Please make sure numbers total 100");
document.getElementById("qty1").value = null;
document.getElementById("qty2").value = null;
document.getElementById("qty3").value = null;
document.getElementById("qty4").value = null;
document.getElementById("qty5").value = null;
document.getElementById("qty6").value = null;
document.getElementById("total").value = null;
return false;
}
if (tot < 100) {
alert("Please make sure numbers total 100");
document.getElementById("qty1").value = null;
document.getElementById("qty2").value = null;
document.getElementById("qty3").value = null;
document.getElementById("qty4").value = null;
document.getElementById("qty5").value = null;
document.getElementById("qty6").value = null;
document.getElementById("total").value = null;
return false;
}
}
</script>

To achieve expected result, use below option
1. Use onkeyup function to check whether input is number or not
2. Use if(tot >100) condition to check value greater than 100
3. if(tot <100) condition to check value less than 100 and alert placed on last field to avoid alert on every field
4.Clear values if conditions are met
HTML:
<form name="myForm" id="form1">
<input oninput="findTotal()" type="text" name="qty" id="qty1" onkeyup="checkinput(this)" /> <br>
<input oninput="findTotal()" type="text" name="qty" id="qty2" onkeyup="checkinput(this)" /><br>
<input oninput="findTotal()" type="text" name="qty" id="qty3" onkeyup="checkinput(this)" /><br>
<input oninput="findTotal()" type="text" name="qty" id="qty4" onkeyup="checkinput(this)" /> <br>
<input oninput="findTotal()" type="text" name="qty" id="qty5" onkeyup="checkinput(this)" /><br>
<input oninput="findTotal()" type="text" name="qty" id="qty6" onkeyup="checkinput(this)" /><br>
<textarea type="text" name="total" id="total" min="100" max="100" readonly></textarea>
</form>
JS:
function findTotal() {
"use strict";
var arr = document.getElementsByName('qty');
var tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value)) {
tot += parseInt(arr[i].value);
}
}
document.getElementById('total').value = tot;
if (tot > 100) {
alert("Please make sure numbers total 100");
for (i = 0; i < arr.length; i++) {
arr[i].value = null;
}
}
if (tot < 100 && arr[5].value) {
alert("Please make sure numbers total 100");
for (i = 0; i < arr.length; i++) {
arr[i].value = null;
}
}
}
function checkinput(x) {
var y = x.value
var regex = /^[0-9]+$/;
if (y.match(regex)) {} else {
alert("Enter number");
x.value = '';
}
}
Codepen- http://codepen.io/nagasai/pen/rLKkBb

Your code has been cliffed off, but just so you know this:
if (tot > 100) {
alert("Please make sure numbers total 100");
return false;
}
if (tot < 100) {
alert("Please make sure numbers total 100");
return false;
}
Is the same as writing this:
if(tot !== 100) {
alert("Please make sure numbers total 100");
return false;
}
Edit:
It's because your event is firing on the oninput event, which fires every time a user types. Use the on submit event which fires when the form is submitted. Make sure to prevent default actions. Comment if this doesn't help you.

One way you may be able to solve this is to exit out of the program if you can't parse all the inputs to ints. If the default value can be parsed to an int, then you may need to add a special case. Edit : Just replace the "return false" with whatever you want to happen when the user enters a non-integer value.
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value)) {
tot += parseInt(arr[i].value);
}
else{
return false;
}
}

Related

Disable button if a sum of number inputs is of certain value (JS)

Given this HTML code:
<body onload="assessSum()">
<input type="number" id="num0" min="0" max="10">
<input type="number" id="num1" min="0" max="10">
<button type="submit" id="sub">Submit</button>
</body>
What would be a function that would disable the submit button, if the sum of the 2 input fields is greater than a certain value?
My JavaScript/Jquery code doesn't seem to work:
function assessSum(){
var total = 0;
var maximum = 5;
var bt = document.getElementById('sub');
$.each($("input"),function(){
total += parseInt($(this).val()) || 0;
});
if(total > maximum){
bt.disabled = true;
}
else{
bt.disabled = false;
}
}
You need to run the function on change event of the inputs.
$(':input').on('change', assessSum);
function assessSum() {
var total = 0;
var maximum = 5;
var bt = document.getElementById('sub');
$("input").each((i, el) => {
total += (parseInt(el.value) || 0);
});
if (total > maximum) {
bt.disabled = true;
} else {
bt.disabled = false;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="num0" min="0" max="10">
<input type="number" id="num1" min="0" max="10">
<button type="submit" id="sub">Submit</button>
The disabling can also be done like this:
$('#sub').attr('disabled', (total > maximum));

Input tag type number for credit card

I have 4 input tags.
<input type="number" class="br1" name="first">
<input type="number" class="br1" name="secound">
<input type="number" class="br1" name="third">
<input type="number" class="br1" name="fourth">
I want to set maxlength (4 numbers) for every input tag. I tried to set maxlength but it doesn't work. Also, when I enter 4 numbers in one input tag, I want to automaticlly input in next input tag.
Thanks.
If you want to use maxlength change type of input to text. Then you can parse all you your inputs strings to a number.
$(".br1").keyup(function () {
if (this.value.length == this.maxLength) {
var $next = $(this).next('.br1');
if ($next.length)
$(this).next('.br1').focus();
else
$(this).blur();
}
});
$(".btn").click(function() {
var string = "";
$(".br1").each(function() {
string += this.value;
});
number = parseInt(string);
console.log(number);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="br1" name="first" maxlength=4>
<input type="text" class="br1" name="secound" maxlength=4>
<input type="text" class="br1" name="third" maxlength=4>
<input type="text" class="br1" name="fourth" maxlength=4>
<button class="btn">toNumber</button>
Use max="9999" and min="0000" to set the maximum value for input type number.
As per http://w3c.github.io/html/sec-forms.html#the-maxlength-and-minlength-attributes maxlength is not valid for input of type number.
You can use input event attached to .br1 elements, .slice() with parameters 0, -1 to remove character if .length of .value is greater than 4
var inputs = document.querySelectorAll(".br1");
for (let input of inputs) {
input.oninput = () => {
if (input.value.length > 4) {
input.value = input.value.slice(0, -1)
}
}
}
<input type="number" class="br1" name="first">
<input type="number" class="br1" name="secound">
<input type="number" class="br1" name="third">
<input type="number" class="br1" name="fourth">
You can do this using only javascript. Also note the maxLength attribute don't work on number, so you may need to use input type='text'
Here is snippet
// get the input
var inputBox = document.getElementsByClassName("br1")
// loop through the array of input
for (var i = 0; i < inputBox.length; i++) {
// creating a closure
(function(x) {
// adding event listener to each of the input
inputBox[x].addEventListener('keydown', function(x) {
// checking value of maxLength
var maxLength = parseInt(this.attributes["maxlength"].value, 10);
// length of the input value
var myLength = this.value.length;
// if both are equal then find the next sibling
if (myLength >= maxLength) {
var next = this.nextElementSibling
// if the next sibling is input, set focus to it
if (next.tagName.toLowerCase() === "input") {
next.focus();
}
}
})
}(i))
}
It as simple as posible, Try this:
$("input[type=number]").keypress(function (e) {
var el = $(this);
var currentValue = el.val();
var char = String.fromCharCode(e.keyCode || e.which);
if (currentValue.length === 3) {
el.val(currentValue + char);
e.preventDefault();
el.next().focus();
} else if (currentValue.length >= 4) {
e.preventDefault();
}
})
input[type=number]{
width:60px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="number" class="br1" name="first">
<input type="number" class="br2" name="first">
<input type="number" class="br3" name="first">
<input type="number" class="br4" name="first">

Mask some digit of Credit Card number in password format

I'm trying to mask Credit Card number in password format in text field.
**** **** **** 1234
Does anyone know of a definitive, reliable way to find this?
If you want to keep all the numbers in one input, you can do something like this:
$("#ccNr").keydown(function(e){
if(e.keyCode != 8){
var length = $(this).val().replace(/ /g,"").length;
if(length < 12){
var val = "";
for(var i = 0; i < length + 1; i++){
val+="*";
if((i+1)%4 == 0){
val+=" ";
}
}
$(this).val(val);
}
if(length < 12 || length >= 16){
e.preventDefault();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="ccNr">
This can definitely be improved. I just wanted to illustrate the idea. The main thing is to override the default behaviour of the keydown event. The e.keyCode != 8 check makes sure that the key pressed isn't the backspace key. You should probably check for some other keys as well if you're going to use this. Also, you may want to ignore non-numerical values.
Well, you could make the first three input types to be of type password and the last one to be text:
function input_onchange(me) {
if (me.value.length < me.getAttribute('maxlength') - 1) {
return;
}
var i;
var elements = me.form.elements;
for (i = 0, numElements = elements.length; i < numElements; i++) {
if (elements[i] == me) {
break;
}
}
elements[i + 1].focus();
}
<form action="post.php" method="post" accept-charset="utf-8">
<input type="password" value="" id="first" size="4" maxlength="4"
onkeypress="input_onchange(this)"/>
<input type="password" value="" id="second" size="4" maxlength="4"
onkeypress="input_onchange(this)"/>
<input type="password" value="" id="third" size="4" maxlength="4"
onkeypress="input_onchange(this)"/>
<input type="text" value="" id="fourth" size="4" maxlength="4"/>
<p><input type="submit" value="Send Credit Card"></p>
</form>

Finding the total or average from four input fields and displaying the value in another input field

I'm trying to use JS to get the sum or the average of four numbers from an input field and then displaying that in another text field. There's a radio button to choose if it's the total or average that is to be displayed.
Here is my html for the form:
<form name="calculate">
Mark: <input type="number" name="number" id="num1"><br>
Mark: <input type="number" name="number" id="num2"><br>
Mark: <input type="number" name="number" id="num3"><br>
Mark: <input type="number" name="number" id="num4"><br>
<input type="radio" id="numTotal" name="choice" value="total">Find total</input>
<input type="radio" id="numAvg" name="choice" value="average">Find average</input>
<br>
<input type="submit" form="calculate" value="Submit" onclick="calculate();">
<input type="reset" form="calculate" value="Reset">
<br>
Result: <input type="text" name="result" id="result" value="" disabled>
</form>
And down here is my JS code:
function calculate(){
var arr = document.getElementsByName("number");
var tot = 0;
var av = 0;
for(var i = 0; i < arr.length; i++) {
if(parseInt(arr[i].value)){
tot += parseInt(arr[i].value);
}
}
av = tot/arr.length;
if(document.getElementById("numTotal").checked) {
document.calculate.getElementbyId("result").value = tot;
}
if(document.getElementById("numAvg").checked) {
document.getElementbyId("result").value = av;
}
}
After running this, the result input field doesn't show the input. Is the error in my script or in the html or both?
<script type="text/javascript">
function calculateFunc() {
var arr = document.getElementsByName("number");
var tot = 0;
var av = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value)) {
tot += parseInt(arr[i].value);
}
}
av = tot / arr.length;
if (document.getElementById("numTotal").checked) {
document.getElementById("result").value = tot;
}
if (document.getElementById("numAvg").checked) {
document.getElementById("result").value = av;
}
return false;
}
</script>
<div class="form">
<form name="calculate">
Mark: <input type="number" name="number" id="num1"><br>
Mark: <input type="number" name="number" id="num2"><br>
Mark: <input type="number" name="number" id="num3"><br>
Mark: <input type="number" name="number" id="num4"><br>
<input type="radio" id="numTotal" name="choice" value="total">Find total</input>
<input type="radio" id="numAvg" name="choice" value="average">Find average</input>
<br>
<br>
Result: <input type="text" name="result" id="result" value="" disabled>
</form>
<input type="submit" value="Submit" onclick="calculateFunc();">
<input type="reset" value="Reset">
</div>
This is work for me in Chrome :)
document.calculate.getElementbyId("result").value = tot;
if(document.getElementById("numTotal").checked) {
document.calculate.getElementbyId("result").value = tot;
}
if(document.getElementById("numAvg").checked) {
document.getElementbyId("result").value = av;
}
need to replace
document.getElementbyId("result").value = tot;
if(document.getElementById("numTotal").checked) {
document.calculate.getElementById("result").value = tot;
}
if(document.getElementById("numAvg").checked) {
document.getElementById("result").value = av;
}

Adding values coming from input in js

When I try to add several values, they just get appended.
These are my inputs (They all look the same):
<input type="number" id="floatOne" required>
This is my script:
<script>
function calcExactFloat(){
var floats = new Array(document.getElementById("floatOne").value, document.getElementById("floatTwo").value,document.getElementById("floatThree").value,document.getElementById("floatFour").value,document.getElementById("floatFive").value,document.getElementById("floatSix").value,document.getElementById("floatSeven").value,document.getElementById("floatEight").value,document.getElementById("floatNine").value,document.getElementById("floatTen").value);
var sum = 0;
for(var i = 0; i < floats.length; ++i){
sum = sum + floats[i];
console.log(sum);
}
Values returned from inputs by .value are considered as string so you should to cast them to float then you can make calculation, so replace the following line :
sum = sum + floats[i];
By :
sum = sum + parseFloat(floats[i]);
Hope this helps.
var floats = new Array(document.getElementById("floatOne").value, document.getElementById("floatTwo").value,document.getElementById("floatThree").value,document.getElementById("floatFour").value);
var sum = 0;
for(var i = 0; i < floats.length; ++i){
sum = sum + parseFloat(floats[i]);
}
result.textContent = sum;
<input type="number" id="floatOne" value='10'>
<input type="number" id="floatTwo" value='10'>
<input type="number" id="floatThree" value='10'>
<input type="number" id="floatFour" value='10'>
<br/>
Result : <span id="result"></span>
The value of input elements if a string, even if that string represent a numerical value. In JavaScript, an "addition" of strings results in concatenation - ('1' + '1') === '11'.
On order to convert the strings to numbers, the simplest way is to use a + before the variable - +a + +b.
Try like this:
var sum = 0;
for(var i = 0; i < floats.length; ++i){
sum = sum + +floats[i];
console.log(sum);
}
you have to use parseFloat
function calcExactFloat(){
var floats = new Array(document.getElementById("floatOne").value, document.getElementById("floatTwo").value,document.getElementById("floatThree").value,document.getElementById("floatFour").value,document.getElementById("floatFive").value,document.getElementById("floatSix").value,document.getElementById("floatSeven").value,document.getElementById("floatEight").value,document.getElementById("floatNine").value,document.getElementById("floatTen").value);
var sum = 0;
for(var i = 0; i < floats.length; i++){
if(floats[i])
sum = sum + parseFloat(floats[i]);
}
alert(sum)
}
<input type="number" id="floatOne" required><br />
<input type="number" id="floatTwo" required><br />
<input type="number" id="floatThree" required><br />
<input type="number" id="floatFour" required><br />
<input type="number" id="floatFive" required><br />
<input type="number" id="floatSix" required><br />
<input type="number" id="floatSeven" required><br />
<input type="number" id="floatEight" required><br />
<input type="number" id="floatNine" required><br />
<input type="number" id="floatTen" required><br />
<input type="button" value="Calc" onclick="calcExactFloat()" />

Categories