JavaScript calculate % of number in <input> field - javascript

I have 2 input fields:
<input id="input1" etc />
<input id="answer" etc />
What I want to do is when a user types in a numerical value (and to restrict them to numbers, no letters or special characters) in "input1" then "answer" input field shows what 0.0015% is of that number (i.e. user types in 35000 so in the answer field it would show 52.5 as that's 0.0015% of the number they entered). This is to be done real time with no submit or calculate button.
How can I do this?

You can do this way to add keyup event on your first input element. I've used vanilla JS though you've used jquery on your fiddle. My fiddle,
function myFunction() {
var inputVal = document.getElementById("input").value;
var answerVal = document.getElementById("answer");
var percentage = (0.0015/100) * parseInt(inputVal,10) * 100;
if(inputVal !== ''){
answerVal.value = (Math.round( percentage * 100 ) / 100).toFixed(1)
}else{
answerVal.value = '';
}
}
input:<input id="input" type="number" onkeyup="myFunction()"/>
answer:<input id="answer" type="text" value=""/>

Your code is almost working perfectly, but it was not working in the given example by you and the reason for that is you have used parseint function of javascript which does not allow decimal values, and to restrict numbers you can use input type number.
$(function(){
$('#pointspossible').on('input', function() {
calculate();
});
$('#pointsgiven').on('input', function() {
calculate();
});
function calculate(){
var pPos = $('#pointspossible').val();
var pEarned = $('#pointsgiven').val();
var perc="";
if(isNaN(pPos) || isNaN(pEarned)){
perc=" ";
}else{
perc = ((pEarned*pPos) / 100);
}
$('#pointsperc').val(perc);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='number' id="pointspossible"/>
<input type='number' id="pointsgiven" />
<input type='text' id="pointsperc" disabled/>

Related

Dropdown with numbers from 1 - 10 and total price below must change

I am trying to create a drop down with numbers from 1 - 10 for example. Once a number is selected, it should change the total amount. However I have not succeeded and not sure what else I should do, please help.
I have got something put together so far.
<div class="checkout">
<input type="number" name="quantity" placeholder="How many would you like to order? (numeric numbers only)" class="quantity price" data-price="49" value="">
<p class="total" style='margin-bottom: 0px;' >Total: <span id="total">R49 per month</span></p>
</div>
<script type='text/javascript'>
$(document).ready(function(){
$(".checkout").on("keyup", ".quantity", function(){
var price = +$(".price").data("price");
var quantity = +$(this).val();
$("#total").text("R" + price * quantity);
})
})
var foo = document.getElementById('.checkout');
foo.addEventListener('focus', function () {
foo.setAttribute('data-value', this.value);
this.value = '';
});
foo.addEventListener('blur', function () {
if (this.value === '')
this.value = this.getAttribute('data-value');
});
</script>
All I need is to change the type from a number to a drop down.

check to see if user input is percentage or dollar

I am fairly new to javascript. Building a custom javascript calculator to set pricing for some products. There is sometimes a fee that is added. This fee is either a percentage of cost or an actual dollar amount. If it is a percentage, it will have a percentage sign. After researching, came up with the following solution that works only if a dollar amount is entered but not if percentage is entered. Is there a better solution?
<form name="calculator">
<input type="text" name="cost" placeholder="Cost" onkeyup="calculate()">
<input type="text" name="fee" placeholder="fee" onkeyup="calculate()">
<br>
<p>The answer is: </p>
<p id="testAnswer"></p>
</form>
<script type="text/javascript" >
function calculate(){
var a = Number(document.calculator.cost.value);
var b = Number(document.calculator.fee.value);
if(b==""){
var result1= a;
} else {
if (/^\d+(\.\d+)?%$/.test(b)) {
result1 =(1+b)*a;
} else {
var result1 = b+a;
}
}
document.getElementById("testAnswer").innerHTML = result1;
}
</script>
Because you are converting the input to a number with:
var a = Number(document.calculator.cost.value);
var b = Number(document.calculator.fee.value);
Any symbols will cause that conversion to fail and therefore you wouldn't be able to perform your test.
var num = Number("234.50%");
console.log(num); // Not a Number
Instead, before doing the conversion, just simply test for the presence of the symbol with .indexOf which returns -1 when the test can't find a match.
var a = document.getElementById("num1");
a.addEventListener("input", function(){
console.clear();
// Always trim leading or trailing spaces from user input
var input = a.value.trim();
var unit = null;
if(input.indexOf("%") > -1){
unit = "Percent";
} else if(input.indexOf("$") > -1) {
unit = "Dollar";
}
console.log(unit); // null until % or $ is entered
// Now that you know what the unit is,
// you can convert to a number. Use parseInt()
// or parseFloat() for this
var inputNum = parseInt(input, 10);
console.log(typeof inputNum, inputNum);
});
<input type="text" id="num1">
Having said all of that, I agree with the comments that a better way to handle this is by not asking the user to input the unit at all and just provide radio buttons:
var a = document.getElementById("num1");
// Set up click event for radio buttons that enables number input
Array.prototype.slice.call(document.querySelectorAll("input[name='unit']")).forEach(function(btn){
btn.addEventListener("click", function(){
a.removeAttribute("disabled");
});
});
a.addEventListener("input", function(){
console.clear();
// Always trim leading or trailing spaces from user input
var input = a.value.trim();
// Just get the value of the selected radio button
var unit = document.querySelector("input[name='unit']:checked").value;
console.log(unit); // null until % or $ is entered
// Now that you know what the unit is,
// you can convert to a number. Use parseInt()
// or parseFloat() for this
var inputNum = parseInt(input, 10);
console.log(typeof inputNum, inputNum);
});
<!-- If you expect only digits, you can use a number type -->
<input type="radio" name="unit" value="%">%
<input type="radio" name="unit" value="$">$
<input type="number" id="num1" disabled>

Input field not updating

I am trying to create a tip calculator using HTML and Javascript and each time the user changes the input field for the meal cost and tip amount, I have to validate whether or not it is a number and if it is, I have to cut down the number to 2 decimal places.
<script>
function validateMealCost(mealCharge){
var mealCost = document.getElementById(mealCharge).value;
if (isNaN(mealCost)){
alert("The cost of the meal has to be a number.");
location.reload();
}
mealCost = mealCost.toFixed(2);
return mealCost;
}
function validateTipPercent(tipPercent){
var tipPercent = document.getElementById(tipPercent).value;
if (isNaN(tipPercent)){
alert("The tip percentage has to be a number.");
location.reload();
}
if (tipPercent >= 1.0){
alert("You are very generous.");
}
tipPercent = tipPercent.toFixed(2);
return tipPercent;
}
function calculateTipAmount(mealCharge, tipPercent){
var tipAmount;
var mealCost = document.getElementById(mealCharge);
var tipPercentage = document.getElementById(tipPercent);
tipAmount = mealCost * tipPercentage;
document.getElementById('tipAmount').value = tipAmount;
}
</script>
<input type="text" id="mealCharge" onchange="validateMealCost('mealCharge');" />
<input type="text" id="tipPercentage" onchange="validateTipPercent('tipPercentage');" />
<button onclick="calculateTipAmount('mealCharge','tipPercentage');">Calculate</button>
<input type="text" id="tipAmount" style="text-align: right;"/>
I don't think it is taking the values that are edited using toFixed() and also the field tipAmount is showing NaN. How can I fix these errors?
<script>
function validateMealCost(mealCharge){
var mealCost = document.getElementById(mealCharge).value;
if (isNaN(mealCost)){
alert("The cost of the meal has to be a number.");
location.reload();
}
mealCost = parseInt(mealCost).toFixed(2);
return mealCost;
}
function validateTipPercent(tipPercent){
var tipPercent = document.getElementById(tipPercent).value;
if (isNaN(tipPercent)){
alert("The tip percentage has to be a number.");
location.reload();
}
if (tipPercent >= 1.0){
alert("You are very generous.");
}
tipPercent = parseInt(tipPercent).toFixed(2);
return tipPercent;
}
function calculateTipAmount(mealCharge, tipPercent){
var tipAmount;
var mealCost = document.getElementById(mealCharge).value;
var tipPercentage = document.getElementById(tipPercent).value;
tipAmount = mealCost * tipPercentage;
document.getElementById('tipAmount').value = tipAmount;
}
</script>
<input type="text" id="mealCharge" onchange="validateMealCost('mealCharge');" />
<input type="text" id="tipPercentage" onchange="validateTipPercent('tipPercentage');" />
<button onclick="calculateTipAmount('mealCharge','tipPercentage');">Calculate</button>
<input type="text" id="tipAmount" style="text-align: right;"/>
The validateMealCost and validateTipPercent functions lacked a parseInt to turn the values to numbers, and the calculateTipAmount function lacked a .value, turning it to NaN.
you need to parse the inputs - all the text inputs will provide strings and therefore cannot be compared to others numbers as a number not can they be in that form nor can they be used for calculations. Also note that even if you have used a number to do calculations, using .toFixed() will convert that number to a string.
For example - you will need to use parseInt or parseFloat which will return a number:
var tipPercent = parseInt(document.getElementById(tipPercent).value);
It is not updating because you need to declare the input before the script. So the simple fix for this would be to move the entire <script> tag to below the last occurrence of <input>.
You can emulate the result using the W3Schools Tryit Editor and pasting a snippet of your code:
<!DOCTYPE html>
<html>
<body>
The content of the body element is displayed in your browser.
<input type="text" id="tipAmount" />
<script>
document.getElementById('tipAmount').value = 5*5;
document.getElementById('tipAmount2').value = 5*5;
</script>
<input type="text" id="tipAmount2" />
</body>
</html>
Notice how the code only updates tipAmount and not tipAmount2.

submitting the different value in jquery

I am having the below code to show input field with phone number in certain format. i.e., If phone number starts with 33,55 or 81 I will show it as (33) 1234-5678. If phone number starts with any other numbers, the format will be (123) 456-7890.
Now, the problem is when I submit the form, it is submitted as (33) 1234-5678. But I should submit 3312345678 and display (33) 1234-5678.
Could someone help me, how could i overcome this issue. I didnt use any jquery plugins;
<input id="criterion" name= "criterion" type="tel" class="inputboxBg" size="15" maxlength="60" style="width:85%;" value="" placeholder="" onkeypress = "submitOnReturn(event);">
jQuery(document).ready(function() {
jQuery("#criterion").change(function () {
var searchBy = jQuery('#smartWirelessSearch').val();
if(searchBy == 'Mobile'){
jQuery(this).attr("criterion", $(this).val());
var twoDigit = jQuery('#criterion').val().substr(0, 2);
var threeDigit = jQuery('#criterion').val().substr(0, 3);
var remainingDigits = jQuery('#criterion').val().substr(2, 10);
if (twoDigit == '33' || twoDigit == '55' || twoDigit == '81') {
jQuery('#criterion').val('('+twoDigit+')'+' '+remainingDigits.substr(0,4)+'-'+remainingDigits.substr(4,8));
} else {
jQuery('#criterion').val('('+threeDigit+')'+' '+remainingDigits.substr(1,3)+'-'+remainingDigits.substr(4,8));
}
}
});
});
You can change the value when the form is submitted, just before it is sent to the server:
$("form").on("submit", function(){
var originalVal = $("#criterion").val();
var newVal = originalVal.replace(/[^\d]/g, '');
$("#criterion").val(newVal);
});
You could have a hidden input that you store the original value of the input before modifying it.
<input id="criterion" name= "criterion" type="tel" class="inputboxBg" size="15" maxlength="60" style="width:85%;" value="" placeholder="" onkeypress = "submitOnReturn(event);">
<input type="hidden" id="org" name="org" />
-
$(document).ready(function() {
$("#criterion").change(function () {
var searchBy = $('#smartWirelessSearch').val();
$('#org').val($(this).val());
if(searchBy == 'Mobile'){
$(this).attr("criterion", $(this).val());
var twoDigit = $('#criterion').val().substr(0, 2);
var threeDigit = $('#criterion').val().substr(0, 3);
var remainingDigits = $('#criterion').val().substr(2, 10);
if (twoDigit == '33' || twoDigit == '55' || twoDigit == '81') {
$('#criterion').val('('+twoDigit+')'+' '+remainingDigits.substr(0,4)+'-'+remainingDigits.substr(4,8));
} else {
$('#criterion').val('('+threeDigit+')'+' '+remainingDigits.substr(1,3)+'-'+remainingDigits.substr(4,8));
}
}
});
});
If you need to have the original cleaned value all the time, there are many ways to do that too. One simple solution is to have clean it by your self everytime input changes.
If so, replace $('#org').val($(this).val()); by $('#org').val($(this).val().replace(/[^\d]/g, ''));
This basically replaces everything that is not a digit with an empty string.
There are two possibilities to solve this, the first is to have a second (extra) hidden input like:
<input id="criterion" name= "criterion" type="tel" class="inputboxBg" size="15" maxlength="60" style="width:85%;" value="" placeholder="" onkeypress = "submitOnReturn(event);">
<input id="criterion_hidden" name= "criterion_real" type="hidden" size="15" maxlength="60" value="" placeholder="" onkeypress = "submitOnReturn(event);">
And populate it in your jquery:
jQuery(document).ready(function() {
jQuery("#criterion").change(function () {
var searchBy = jQuery('#smartWirelessSearch').val();
if(searchBy == 'Mobile'){
jQuery(this).attr("criterion", $(this).val());
var twoDigit = jQuery('#criterion').val().substr(0, 2);
var threeDigit = jQuery('#criterion').val().substr(0, 3);
var remainingDigits = jQuery('#criterion').val().substr(2, 10);
$("#criterion_hidden").val(twoDigit + remainingDigits); //update it here.
if (twoDigit == '33' || twoDigit == '55' || twoDigit == '81') {
jQuery('#criterion').val('('+twoDigit+')'+' '+remainingDigits.substr(0,4)+'-'+remainingDigits.substr(4,8));
} else {
jQuery('#criterion').val('('+threeDigit+')'+' '+remainingDigits.substr(1,3)+'-'+remainingDigits.substr(4,8));
}
}
});
});
The other solution is to change the value on the server side (PHP?) by using a replace with a regular expression such as /[^\d]/g.
On submit of the form replace input value of ( ) - with empty string "".
I would suggest two solutions:
1. Toggle Format
With this solution, you either show the formatted value in the input, or the clean digit-only value. So you would take care to show the digit-only value when the form is submitted, but also when the user edits the value (as suggested by #Rune FS):
jQuery(function($) {
function cleanMobile() {
if ($('#smartWirelessSearch').val() == 'Mobile') {
// Strip all non-digit characters
$("#criterion").val($("#criterion").val().replace(/[^\d]/g, ''));
}
}
function formatMobile() {
if ($('#smartWirelessSearch').val() == 'Mobile') {
// Apply format after first stripping all non-digit characters
$("#criterion").val($("#criterion").val()
.replace(/[^\d]/g, '')
.replace(/(33|55|81|...)(.*?)(....)$/, '($1) $2-$3'));
}
}
$("#myform").submit(cleanMobile);
$("#criterion").blur(formatMobile).focus(cleanMobile).keypress(function(e) {
if (e.keyCode == 13) {
$(this).closest('form').submit();
}
});
// Set initial format correctly on page load
formatMobile();
}, jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
<select id="smartWirelessSearch">
<option value="Mobile">Mobile</option>
</select>
<input id="criterion" name="criterion" type="tel" class="inputboxBg"
size="15" maxlength="60" style="width:85%;" value="" placeholder="">
<input type="submit" value="submit">
</form>
Run the snippet to see how it responds to focus and submit.
Note that the code above also:
Uses a regular expression to format the number;
attaches the keypress handler via code instead of the element's onkeypress attribute;
defines functions for the format manipulations so these can be referenced in blur, focus and submit events;
defines a dummy smartWirelessSearch element so the code is compatible with your form;
gave the form an id myform, which you should replace with yours.
2. Use Hidden Input
If you do not want the input value to visibly change at form submission, you could add a hidden input and give that the digit-only value, like this:
<input id="criterionClean" name="criterionClean" type="hidden">
<input id="criterion" name= "criterion" type="tel" class="inputboxBg" size="15"
maxlength="60" style="width:85%;" value="" placeholder=""
onkeypress="submitOnReturn(event);">
In your Javascript add one line:
if(searchBy == 'Mobile'){
// ... your code ...
// Then pass the digits only in the hidden input
$('#criterionClean').val($(this).val().replace(/[^\d]/g, ''));
}
Now you'll submit both the formatted and the cleaned value. Your server code could then use the clean digit-only value.
If you prefer the clean value to be called #criterion, then swap the names of the two inputs in html and in your code.

How to have a range to two input boxes where it will be divided after...

I have this 2 input fields which automatically divides the first input by the second one.
First input field:
<input type="text" name="MyName1" id="1" value="1000.00" onkeyup="getValues(1)" size="10">
Second input field:
<input type="text" name="MyName2" id="2" value="26" onkeyup="getValues(2)" size="10">
Output:
<input type="text" id="main" name="MyOutput" size="5" value=38.46>
And my script:
<script language="javascript">
function getValues(val){
var numVal1=parseFloat(document.getElementById("1").value,10);
var numVal2=parseFloat(document.getElementById("2").value,10);
var totalValue = numVal1 / numVal2;
document.getElementById("main").value = totalValue.toFixed(2);
}
</script>
How can I add a min/max range for both input fields so that the only range accepted on the first input field will be from 200-1000, and the second input field will be from 1-26. An alert would be also cool if the value is not within the specified range.
Thanks!!!
Do a simple interval-bound check:
function getValues(val){
var numVal1=parseFloat(document.getElementById("1").value,10);
var numVal2=parseFloat(document.getElementById("2").value,10);
var totalValue = numVal1 / numVal2;
if(numVal1 >= 200 && numVal1 <= 1000){
document.getElementById("1").style.borderColor='red';
}else{
document.getElementById("1").style.borderColor='';
}
if(numVal2>= 1&& numVal2 <= 26){
document.getElementById("2").style.borderColor='red';
}else{
document.getElementById("2").style.borderColor='';
}
document.getElementById("main").value = totalValue.toFixed(2);
}

Categories