Validate sum of two input fields - javascript

I am trying to calculate sum of two fields and validate them. Basically, I need sum of the two input field's value is greater than 100, and want to display a prompt if the sum is less than 100.
So far, I have this:
<input type="text" class="input" id="value1">
<input type="text" class="input" id="value2">
<script>
$(document).ready(function(){
var val1 = $("#value1").val();
var val2 = $("#value2").val();
});
</script>
However, I don't know how to validate the result and display a prompt if the sum of these two inputs is less than 100.
Can you please point me in the right direction?

You need to use focusout to get the real-time sum and alert the user if sum is less than 100, You can add keyup events too, but that won't make sense as it would start alerting as soon as you type. IMO, you should have a button, and on click on that button, the calculation and validation shoud be triggered
And if you already have values populated in the input fields, you just need to call / trigger the focusout or click event of the button:
:
$("#value1, #value2").on('focusout', function() {
var value2 = parseInt($("#value2").val()) > 0 ? parseInt($("#value2").val()) : 0;
var value1 = parseInt($("#value1").val()) > 0 ? parseInt($("#value1").val()) : 0
var sumOfValues = value1 + value2;
if (sumOfValues < 100) {
console.log('Your sum is ' + sumOfValues + ' which is less than 100');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="input" id="value1">
<input type="text" class="input" id="value2">
With button:
$("button").on('click', function() {
var value2 = parseInt($("#value2").val()) > 0 ? parseInt($("#value2").val()) : 0;
var value1 = parseInt($("#value1").val()) > 0 ? parseInt($("#value1").val()) : 0
var sumOfValues = value1 + value2;
if (sumOfValues < 100) {
console.log('Your sum is ' + sumOfValues + ' which is less than 100');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="input" id="value1">
<input type="text" class="input" id="value2">
<button>Calculate</button>

Wrap your inputs in a form
Add submit button to get values into variables
Write condition logic
Add an output html node to output the result

$(document).ready(function() {
var val1 = parseInt($("#value1").val());
var val2 = parseInt($("#value2").val());
var sum = val1 + val2;
if(sum > 100) {
alert(sum+ ' is greater than 100')
} else {
alert(sum + ' is less than 100')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" class="input" id="value1" value="70">
<input type="text" class="input" id="value2" value="50">
Check this example.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function myFunction() {
var val1 = $("#value1").val();
var val2 = $("#value2").val();
var sum = parseInt(val1) + parseInt (val2);
if(sum > 100) {
alert('Sum '+sum+ ' is greater than 100')
} else {
alert('Sum '+sum+ ' is less than 100')
}
}
</script>
</head>
<body>
<input type="text" class="input" id="value1">
<input type="text" class="input" id="value2">
<button type="button" onclick="myFunction()">Check</button>
</body>
</html>

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<input type="text" class="input" id="value1">
<input type="text" class="input" id="value2">
<button type="sumbit" name="submit" id="submit">check sum</button>
<p id="resultMessage"></p>
<script>
$(document).ready(function() {
// on button pressed
$('#submit').on('click', function() {
var val1 = $("#value1").val();
var val2 = $("#value2").val();
// numeric validation
if (!isNumeric(val1) || !isNumeric(val2)) {
$('#resultMessage').text('Some field contains not a number');
return;
}
// + operator converts input Strings to Number type
var sum = +val1 + +val2;
if (sum > 100) {
// if sum greather than 100
$('#resultMessage').text('Sum is greather than 100 (' + sum + ')');
} else if (sum < 100) {
// some code if sum less than 100 ...
$('#resultMessage').text('Sum is less than 100 (' + sum + ')');
} else {
// sum is 100
$('#resultMessage').text('Sum equals 100');
}
});
// function for numeric validation
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
});
</script>
</body>
</html>

Related

How to limit two inputs with custom maxlength?

How to limit two inputs with custom maxlength ?
I am setting a custom limit $limit = "500"; and trying to limit user words in two inputs. I want to limit first input maxlength and count words in first input, than limit second input maxlength with words left from my custom limit.
I want to set length together max length 500, one can have max 100 and one can have max 400.
and if first input has less words than 100, then add rest of the words left to the second input max length.
like : first input has 95 words in, 5 words left to reach limit.
then change second input maxlentgh to 405,
I create inputs like this :
function maxLength(el) {
if (!('maxLength' in el)) {
var max = el.attributes.maxLength.value;
el.onkeypress = function() {
if (this.value.length >= max) return false;
};
}
}
maxLength(document.getElementById("title"));
function validateLength(el, word_left_field, len) {
document.all[word_left_field].value = len - el.value.length;
if (document.all[word_left_field].value < 1) {
alert("You can add max " + len + " words .");
el.value = el.value.substr(0, len);
document.all[word_left_field].value = 0;
return false;
}
return true;
}
<input type="text" id="title" name="title" maxlength="100" onChange="return validateLength(this, 'word_left', 100);" onKeyUp="return validateLength(this, 'word_left', 100);">
<input type="text" name="word_left" value="100" style="width: 25;" readonly="true" size="3">
<input type="text" id="subject" name="subject" maxlength="400" onChange="return validateLength(this, 'word_left', 400);" onKeyUp="return validateLength(this, 'word_left', 400);">
<input type="text" name="word_left" value="400" style="width: 25;" readonly="true" size="3">
so total of both inputs is 500.
I tried to set html 5 attributes pattern=".{59,60}" but they are same as setting attrbutes min and length.
But my javascript is limiting first input.
I tried several methods but didn't have a chance to make it work, would be to long question I didnt put all on here.
I belive that you need something like this:
var _maxLength = 500;
var _lengthInput = 0;
var input1 = document.getElementById("input1");
var input2 = document.getElementById("input2");
var p = document.getElementById("total");
p.innerHTML = _maxLength;
input1.addEventListener("focus", function(e) {
this.maxLength = _maxLength + this.value.length;
_lengthInput = this.value.length;
});
input1.addEventListener("blur", function(e) {
if (_lengthInput == this.value.length)
return;
if (_lengthInput > this.value.length) {
_maxLength += _lengthInput - this.value.length;
} else {
_maxLength -= this.value.length - _lengthInput;
}
total.innerHTML = _maxLength;
});
input2.addEventListener("focus", function(e) {
this.maxLength = _maxLength + this.value.length;
_lengthInput = this.value.length;
});
input2.addEventListener("blur", function(e) {
if (_lengthInput == this.value.length)
return;
if (_lengthInput > this.value.length) {
_maxLength += _lengthInput - this.value.length;
} else {
_maxLength -= this.value.length - _lengthInput;
}
total.innerHTML = _maxLength;
});
Input 1 <input type="text" id="input1">
<br /> Input 2 <input type="text" id="input2">
<br />
<p>Characters remaining: <span id="total"></span> </p>
I hope below code helps you,
$(document).ready(function () {
$("#subject").on("keypress", function () {
var titleLength = $("#title").val().length;
var titleMaxLength = $("#title").attr("maxLength");
var titleWordLeft = titleMaxLength - titleLength
var subjectLength = $("#subject").data("charlength");
var subjectMaxLength = titleWordLeft + subjectLength;
$("#subject").attr("maxLength",subjectMaxLength);
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="title" name="title" maxlength="100">
<input type="text" name="word_left" value="100" style="width: 25;" readonly="true" size="3">
<input type="text" id="subject" name="subject" data-charlength="400">
<input type="text" name="word_left" value="400" style="width: 25;" readonly="true" size="3">

how to insert id="getdobval" into input value?

I want to insert a value into <input type="text" id="getdobtval"> when I am selecting a range value.
For showing output in browser am using <span id="getdobtval"></span> instead of this span I want insert into text. How can I solve this using javascript?
jQuery(document).ready(function() {
$('#slider-bottom').slider().on('slide', function(ev) {
var finalvalue = '';
var finalbtvalue = '';
var finalbtprice = '';
var finalbitvalue = '';
finalbtprice = 250;
var newVal = $('#slider-bottom').data('slider').getValue();
var textval = parseInt(newVal);
if (textval >= 600 && textval < 6000) {
finalvalue = 0.075;
finalbitvalue = textval * finalvalue;
} else if (textval >= 6000 && textval < 30000) {
finalvalue = 0.070;
finalbitvalue = textval * finalvalue;
} else if (textval >= 30000) {
finalvalue = 0.065;
finalbitvalue = textval * finalvalue;
}
finalbtvalue = finalbitvalue / finalbtprice;
if (finalbtvalue) {
$("#getdobtval").html("<strong>" + finalbtvalue.toFixed(8) + "</strong>");
}
});
$('#slider-bottom').sliderTextInput();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
<input id="slider-bottom" type="text" name="hrate" data-slider-min="600" data-slider-max="100000" data-slider-step="1" data-slider-value="600" data-slider-tooltip="show" />
<span id="getdobtval"></span>
<input type="text" id="getdobtval" name="getdobtval">
<input type="submit" name="buynow">
</form>
Create a hidden input box with different id like dobtval
<form action="" method="post">
<input id="slider-bottom" type="text" name="hrate" data-slider-min="600" data-slider-max="100000" data-slider-step="1" data-slider-value="600" data-slider-tooltip="show" />
<span id="getdobtval"></span>
<input type="hidden" id="dobtval" name="dobtval"/>
<input type="submit" name="buynow">
</form>
And in JS use,
....
if (finalbtvalue) {
$('#dobtval').val(finalbtvalue.toFixed(8));// set value in input
$("#getdobtval").html("<strong>" + finalbtvalue.toFixed(8) + "</strong>");
}
....
id must be unique, but if you want same HTML then differentiate your elements by their tag name like,
$('span#getdobtval').html('....'); // use html() span/div
$('input#getdobtval').val('....'); // use val() for input/textarea

Dynamically update the value of form as user types input before submitting

I need help dynamically updating the value of form submit as user types input field.
<form>
<input type="text" name="number" id="number" value = 0 />
<input type="submit" id="submit">
</form>
<script>
var amount = 100;
var number = document.getElementById('number').value;
var total = amount + number;
var a = document.getElementById("submit");
a.value = "Pay $" + total;
</script>
Right now, the value of submit is "Pay 100". But when user enters 4 in number field, I want it to say "Pay 104" as he types 4. I also want user to delete and enter different number and the value changes accordingly. How would I achieve this? Thanks in advance.
Try this..
document.getElementById('number').addEventListener("input", function(){
if(this.value.length && !isNaN(parseInt(this.value))){
var total = amount + parseInt(this.value);
submit.value = "Pay $"+ total;
}
}, false);
var amount = 100;
var submit = document.getElementById("submit");
document.getElementById('number').addEventListener("input", function(){
if(this.value.length && !isNaN(parseInt(this.value))){
var total = amount + parseInt(this.value);
submit.value = "Pay $"+ total;
}
}, false);
<form>
<input type="text" name="number" id="number" value = 0 />
<input type="submit" id="submit">
</form>

Javascript total return NaN for 4 digits num

Here is the javascript for calculating the price of the item the problem is that
whenever the price is 4 digits the value that return is NaN.
here's my hidden field for the price:
<input type="hidden" name="price" id="price"class="price" value="4500"readonly >
here's for my quantity field
<input type="number" name="quant" id="quant" value="2" />
here's for my shipment fee
<select id="shipment" onchange="myFunction3()" name="shipment2" disabled>
<option value="100" data-quantity="1">1 for 100 pesos </option>
</select
here's for the total price
<input type="text" id="demo" name="total_price" style="margin-top:10px;margin-left:5px;" readonly>
Script for changing the value of shipment
<script type="text/javascript">
document.getElementById('quant').addEventListener("keyup", function(){
var value = parseInt(this.value, 20),
selectEle = document.getElementsByTagName('select')[0],
options = selectEle.options,
selectedNum = 0;
for(var i = 0; i < options.length; i++) {
//checking the exact string with spaces (" " + value + " ")
if(options[i].textContent.indexOf(" " + value + " ") > -1) {
selectedNum = i;
}
}
selectEle.selectedIndex = selectedNum ? selectedNum : 0;
}, false);
</script>
Calculating all the values
function myFunction3() {
var y= document.getElementById("shipment").value;
return y;
}
<script>
$("#price,#quant,#shipment").keyup(function () {
if(+myFunction3() =="" )
{
$('#demo').val(0);
}
else if($('#trigger')=="checked") //this is the problem
{
$('#demo').val($('#price').val() * $('#quant').val() ;
}
else
{
$('#demo').val($('#price').val() * $('#quant').val() + +myFunction3());
}
});
</script>
Not sure if this was just typed incorrectly in here, but you have a syntax error (missing closing parenthesis) near the problem area:
$('#demo').val($('#price').val() * $('#quant').val() ;
Should be:
$('#demo').val($('#price').val() * $('#quant').val());
I think it would be much better to ensure you aren't working with strings before you do math on them:
var price = parseInt($('#price').val(), 10);
var quantity = parseInt($('#quant').val(), 10);
$('#demo').val(price * quantity);
You could go further and ensure that neither of them are NaN prior to working with them:
var price = parseInt($('#price').val(), 10);
var quantity = parseInt($('#quant').val(), 10);
if(!isNaN(price) && !isNaN(quantity)) {
$('#demo').val(price * quantity);
} else {
alert('Please enter numbers only!');
}

How do I get the sum of radio buttons groups using parameters instead of values

I have multiple sets of radio buttons where the selected values of each set need to be added and displayed to the user. So far I have been changing the values in the function in a switch statement to handle the addition.
<form name="config" id="config">
<div class="row-fluid">
<h3>Memory</h3>
<input type="radio" name="section1" value="4gb" onclick="changePrice(0)" checked>4gb<br>
<input type="radio" name="section1" value="8gb" onclick="changePrice(100)">8gb (+$100)<br>
<input type="radio" name="section1" value="16gb" onclick="changePrice(200)">16gb (+$200)
</div>
<div class="row-fluid">
<h3>Primary Hard Drive</h3>
<input type="radio" name="section2" value="dell" onclick="changePrice(0)" checked>Dell<br>
<input type="radio" name="section2" value="asus" onclick="changePrice(100)">Asus(+$100)
</div>
</form>
<div id="price"></div>
The script I am using right now is
var displayPrice = document.getElementById("price");
var baseNum = 200;
displayPrice.innerHTML = baseNum;
function(changePrice){
var val1, val2;
switch(document.config.section1.value){
case "4gb":
val1 = 0;
break;
case "8gb":
val1 = 100;
break;
case "16gb":
val1 = 200;
break;
default:
val1 = 0;
}
switch(document.config.section2.value){
case "dell":
val1 = 0;
break;
case "asus":
val1 = 100;
break;
default:
val1 = 0;
}
var sum = val1 + val2 + baseNum;
displayPrice.innerHTML = sum;
}
Is there a way I can do these calculations using the parameters passed through the changePrice function (so I don't have to change the values in the switch statements)?
Here's how to do this without jQuery.
You'll need to tell the changePrice function which section it should change the price for so you'll need to change the calls to look like this changePrice(1, 100) where 1 is the section and 100 is the price change. Then you can collect all the section prices individually and sum them like so:
var displayPrice = document.getElementById("price");
var baseNum = 200;
displayPrice.innerHTML = baseNum;
var sections = {};
function changePrice(section,val){
// add or update the section value
sections[section] = val;
// start with the base price
var sum = baseNum;
// loop over all the sections and add them to the base price
for(var key in sections) {
sum = sections[key] + sum;
}
displayPrice.innerHTML = sum;
}
Here's a jsfiddle
If you change your function definition to the following, it will take in your parameter.
function changePrice(val1)
If you could change your the value attribute on each of your input fields to contain your increment value, it would make the process of calculating your sum much easier. (This may not be appropriate to the problem you are trying to solve.
Basic solution with jQuery
var sum = $("input[name=section1]").val() + $("input[name=section2]").val();
If your list is very long, you could iterate over your radio button sets with jQuery
var sum = 0;
$("input[type=radio]").each(function(){sum += $(this).val();});
<html>
<head>
<script type="text/javascript">
function DisplayPrice(price){
var val1 = 0;
for( i = 0; i < document.form1.R1.length; i++ ){
if( document.form1.R1[i].checked == true ){
val1 = document.form1.R1[i].value;
}
}
var val2 = 0;
for( i = 0; i < document.form2.R2.length; i++ ){
if(document.form2.R2[i].checked == true ){
val2 = document.form2.R2[i].value;
}
}
var sum=parseInt(val1) + parseInt(val2);
document.getElementById('totalSum').innerHTML=sum;
}
</script>
</head>
<body>
Choose a number:<br>
<form name="form1" id="form1">
<br>
R1 <input id="rdo_1" type="radio" value="5" name="R1" onClick="DisplayPrice(this.value);" checked>5
<br>
R1 <input id="rdo_2" type="radio" value="10" name="R1" onClick="DisplayPrice(this.value);">10
<br>
</form>
Choose another number:<br>
<form name="form2" id="form2">
<br>
R2 <input id="rdo_1" type="radio" value="15" name="R2" onClick="DisplayPrice(this.value);" checked>15
<br>
R2 <input id="rdo_2" type="radio" value="20" name="R2" onClick="DisplayPrice(this.value);">20
<br>
</form>
Your total is Rs = <span name="totalSum" id="totalSum" > 20</span>
</body>
</html>

Categories

Resources