calculation based on input field for a result on the fly - javascript

This is an extension to this thread.
My situation:
I need a user to enter a decimal value (ie 0.05) and show a simple calculation on the fly as the user types (or pastes). The example shown works for whole numbers but not when a decimal is entered into the input field.
I need to display the result in multiple places. I assumed I could just update getElementById to getElementByClass but that didn't work.
My Code:
<input type="text" name="capname" id="numberField" value="0.07" maxlength="5" />
<span name="mpd" id="mpdresult" class="mpdresult" ></span>
<span class="mpdresult" ></span> (second display)
<script>
window.onload = function() {
var base = 500;
var numberField = document.getElementById('numberField');
numberField.onkeyup = numberField.onpaste = function() {
if(this.value.length == 0) {
document.getElementById('mpdresult').innerHTML = '';
return;
}
var number = parseInt(this.value);
if(isNaN(number)) return;
document.getElementById('mpdresult').innerHTML = number * base;
};
numberField.onkeyup(); //could just as easily have been onpaste();
};
</script>

please use
var number = parseFloat(this.value);
instead of
var number = parseInt(this.value);

use ParseFolat for Decimal Numbers
document.write(parseFloat("10.33") + "<br>");
ParseFloatSample

Use parseFloat instead of parseInt. http://jsfiddle.net/janCY/
there is no such function getElementByClass. There is getElementsByClassName, it returns array with elements. But why don't use JQuery?

Related

Showing an image based on a number range in Javascript

I am trying to create a javascript program that prompts the user for a number. If a user puts in a number that is less then 21, an image of soda will show. If the number is 21 or greater, the image is beer. There is an image of a bar that is shown when the page loads. Negatives and non-numbers are not allowed in the code. I have worked on this code for over a couple of days and the code does run. The only problem I have with it is that it will say that any input is an invalid entry. I have looked around for any solutions and I'm not sure what to do. I am new to javascript and any help would be appreciated.
Below is the javascript I am using:
function start()
{
let button1 = document.getElementById("button1");
button1.onclick = toggleContent;
}
function toggleContent()
{
let number = document.getElementById('number');
let liquid = document.getElementById('Bar');
if parseInt(number <= 20)
{
liquid.src = 'assets/Soda.png';
liquid.alt = 'Spicy water';
}
else if (number >= 21)
{
liquid.src = 'assets/Beer.png';
liquid.alt = 'Angry Juice';
}
else if (isNaN(number) || number < 0)
{
alert("Invalid Entry. Enter a Number.")
}
}
window.onload = start;
Here is the HTML code that goes with it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ID Check?</title>
<script src="scripts/pt2script.js"></script>
</head>
<body>
<img id="Bar" src="assets/barimage.png" alt="Image of a Bar Sign.">
<p>Enter a number into the text box.</p>
<input type="text" id="number" value="Enter a number...">
<button onclick="toggleContent()" id="button1">Submit</button>
</body>
</html>
You need to get the value from input and convert it to a number by using an unary plus +.
function start() {
let button1 = document.getElementById("button1");
button1.onclick = toggleContent;
}
function toggleContent() {
let number = +document.getElementById('number').value; // take value as a number
let liquid = document.getElementById('Bar');
if (isNaN(number) || number < 0) { // move exit condition to top and exit early
alert("Invalid Entry. Enter a Number.")
return;
}
if (number <= 20) { // condition without parseint
liquid.src = 'assets/Soda.png';
liquid.alt = 'Spicy water';
} else { // no need for another check
liquid.src = 'assets/Beer.png';
liquid.alt = 'Angry Juice';
}
}
window.onload = start;
<img id="Bar" src="assets/barimage.png" alt="Image of a Bar Sign.">
<p>Enter a number into the text box.</p>
<input type="text" id="number" placeholder="Enter a number..."><!-- use placeholder -->
<button onclick="toggleContent()" id="button1">Submit</button>
You are attempting to convert a boolean to an integer. This will not work sense (num >= 20) or whatever will evaluate to true or false, and not a number (NaN). You can convert the value to a number before trying to do a logical comparison. I'd do something such as:
$('.btn').on('click', function() {
let val = $('#num').val();
val = parseInt(val);
if(val >= 21) {
$('img').attr('src', '/path-to-soda');
}
else {
$('img').attr('src', '/other-path');
}
});
As soon as an event triggers your number comparison I would instantly convert it to a number (i'm assuming you are using a number input which will do this for you), and then perform the logical operation. If you're using a number input (which again, i'm just assuming), you won't even need to convert the value to a number. That's only necessary if you're using a text input or something along those lines.

Javascript form value restriction

I am trying to create a form which will store values in an empty array but the values must be between 0 to 5 and comma separated. the problem is it alerts if values is more than 5 but still stores the value in the array. I want it to alert and then restore the form value.
Here is my code:
<form name ="form1" onsubmit="return validateForm()">
<input type="number" name="text" id="inputText" name="inputText" />
<button onclick="pushData();">Insert</button>
<p id="pText"></p>
</form>
And javascript:
function validateForm () {
var form = document.forms["form1"]["inputText"].value;
if(form <0 && form >= 6) {
alert('value should must be between 0 to 5');
return false;
}
}
// create an empty array
var myArr = [];
function pushData() {
// get value from the input text
var inputText = document.getElementById('inputText').value;
// append data to the array
myArr.push(inputText);
var pval = "";
for(i = 0; i < myArr.length; i++) {
pval = pval + myArr[i];
}
// display array data
document.getElementById('pText').innerHTML = "Grades: " + pval ;
}
Try
if (form <0 || form >= 6)
I think it may work better if you reorganize where the functions are being bound.
Event propagation order:
The button is clicked, and the value is pushed into the array.
The form's submit event triggers, and validates the values, but it's too late.
There are many ways to approach this one, but the simplest would be to call pushData at the end of your validateForm.
Adjusted the condition, because there's no way for a number to
be less than 0 AND greater than or equal to 6 at the same time.
Also added event.preventDefault to stop form submission.
JavaScript
function validateForm (event) {
event.preventDefault();
var form = document.forms["form1"]["inputText"].value;
if (form < 0 || form > 5) {
alert('value should must be between 0 to 5');
return false;
}
pushData();
}
HTML
<form name="form1" onsubmit="validateForm(event)">
<input type="number" id="inputText" />
<button type="submit">Insert</button>
<p id="pText"></p>
</form>
JSFiddle
Note that per the MDN:
A number input is considered valid when empty and when a single number
is entered, but is otherwise invalid.
With this particular form element you may add min and max attributes so that the user must enter a value within a specified range. Therefore, the current contents of the OP's validateForm() function are superfluous. Additionally, that function has a problematic line of code:
if(form <0 && form >= 6) {
You cannot have a value that is both less than zero and greater than or equal to six. Use instead a logical OR, i.e. "||" operator for the logic to work.
The following code allows for a user to select numeric values in the range that the OP specifies and then it displays them in a comma-separated format, as follows:
var d = document;
d.g = d.getElementById;
var pText = d.g('pText');
pText.innerHTML = "Grades: ";
var inputText = d.g("inputText");
var myArr = [];
function pushData() {
var notrailingcomma = "";
myArr.push(inputText.value);
if (myArr.length > 1) {
notrailingcomma = myArr.join(", ").trim().replace(/,$/g,"");
pText.innerHTML = "Grades: " + notrailingcomma;
}
else
{
pText.innerHTML += inputText.value;
}
}
d.forms["form1"].onsubmit = function(event) {
event.preventDefault();
pushData();
};
p {
padding: 1em;
margin:1em;
background:#eeeeff;
color: #009;
}
<form name="form1">
<input type="number" id="inputText" name="inputText" min=0 max=5 value=0>
<button type="submit">Insert</button>
</form>
<p id="pText"></p>
A couple of points with respect to the form:
The OP's HTML has an error in the input field: it has two names. I dropped the one with a name of "text".
I like what #thgaskell recommends with respect to changing "Insert" into a submit button, preventing the default action of submitting the form, and associating pushData with the form's onsubmit event. So, I've modified the code accordingly.

How to stop Infinity showing during input

I have created a form which works out a sum depending on the users input, this works fine but during the input stage i get the infinity property displayed in the total. Is there anyway of avoiding this?
I'm by no means a Javascript expecrt so any help would be appreciated. Here is the code.
<div class="wrapper">
<form id="convert">
<input type="text" name="child" onkeyup="formChanged()" onchange="formChanged()"/>
<input type="text" name="parent" onkeyup="formChanged()" onchange="formChanged()"/>
<div id="final"></div>
</form>
<script>
function formChanged() {
var first = document.getElementsByName("child")[0].value;
var second = document.getElementsByName("parent")[0].value;
var third = first / second;
var four = third * 100;
document.getElementById("final").innerHTML = four+"%";
}
</script>
</div><!-- /.wrapper -->
Don't divide by zero.
What you want to do when second is zero is up to you. But probably the easiest way to handle it is to just not do the calculation and not write anything in final unless you have a non-zero value from second.
In addition, you might want to check for NaN as well. If somebody writes a something in either textbox that is not actually a number, you will end up with NaN% in your output. (here you can use isNaN or you can compare the results of parsing your values with NaN).
So you could do something like:
var first = parseFloat(document.getElementsByName("child")[0].value);
var second = parseFloat(document.getElementsByName("parent")[0].value);
if (first !== NaN && second) { // note NaN and 0 are both falsy
// do your calculation here
}
You're going to need to do some validation on your values first. Your calculation only makes sense with numeric values and you're going to have to ensure that you don't try to calculate it if your second variable == 0.
In this case, I wouldn't try to parse/validate the inputs. Do as few as possible, and assume valid inputs.
Just test wether you get a valid output, before showing the result.
function isValidNumber(v){
//!NaN && !Infinity
return v===v && v !== Infinity && v !== -Infinity;
}
//cast the inputs to a valid number
function number(v){
//return +String(v).replace(",", ".");
return +v;
//return +v || 0;
}
function formChanged() {
var first = document.getElementsByName("child")[0].value;
var second = document.getElementsByName("parent")[0].value;
var result = 100 * number(first) / number(second);
document.getElementById("final").innerHTML = isValidNumber(result)?
Math.floor(result) + "%": //I have a valid result
""; //values have changed, but sth. went wrong
}
I think that will work for you.
<div class="wrapper">
<form id="convert">
<input type="text" name="child" onkeyup="formChanged()" onchange="formChanged()"/>
<input type="text" name="parent" onkeyup="formChanged()" onchange="formChanged()"/>
<div id="final"></div>
</form>
<script>
function formChanged() {
var first = document.getElementsByName("child")[0].value;
var second = document.getElementsByName("parent")[0].value;
if(second == ""){second=1};
if(first != "" && second != ""){
var third = parseInt(first) / parseInt(second);
var four = parseInt(third) * 100;
document.getElementById("final").innerHTML = four+"%";
}
}
</script>
</div><!-- /.wrapper -->
Thanks

if input field is not a number OR not empty replace with a number

I have an input field that I am monitoring for changes using an .on('input') function as this covers .change and .keyup.
There is no submit button yet I just want to change the behaviour of the input field depending on what is entered.
I will validate server side later and I'm using html5 type='number'.
I only want the field to be able to hold a number, or it can be empty. The user might want to empty the contents to type the number 15 for example.
However I don't want any other characters to be accepted - if they are entered, a prompt should show notifying the user of this and the field is defaulted back to it's starting value of 1.
HTML
<input type="number" class="input-field" placeholder="" value="1" min="1">
JS
$(document).ready(function ($) {
var num = $('input[type="number"]').val();
$('input[type="number"]').on('input', function () {
var num = $(this).val();
if (num < 1 || isNaN(num) || num !== '') {
alert(num + ' is not a number or is less than 1');
$(this).val(1);
}
});
});
I have tried with the above code and it doesn't allow for an empty field. I've also tried if (num < 1 || isNAN(num) || num.length != 0) {
do I need to use .replace() with a Regexr. I've been looking at a few questions on here like here but I'm not sure thats what I'm looking for considering I'm testing for an empty string.
JSFIDDLE
You can use the constraint validation API:
$('input[type="number"]').on('input', function () {
if (!this.validity.valid) {
alert(this.value + ' is not a number or is less than 1');
this.value = 1;
}
});
$('input[type="number"]').on('input', function () {
if (!this.validity.valid) {
alert(this.value + ' is not a number or is less than 1');
this.value = 1;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" class="input-field" placeholder="" value="1" min="1">
However, note that this behavior is obtrusive. If an user types the wrong key, you will annoy him with a modal dialog and will clear the number.
Consider doing nothing. HTML5 browsers won't send the form if the input is not valid.
The HTML5 answer is definitely more elegant.
But if you want to offer more support, this is usually the route I take when trying to verify numbers.
Note that I am using data-min attribute but if you want to switch you can always use $.attr() to grab your min="" attribute.
$(document).ready(function ($) {
$('input[type="number"]').on('change', function () {
var min = parseInt(this.dataset.min),
num = isNaN(parseInt(this.value)) ? 0 : parseInt(this.value),
clamped = Math.max(num, min);
if(num != clamped) {
alert(num + ' is less than 1');
this.value = clamped;
}
});
});
jsfiddle

Javascript calculator as users type numbers

I'm a noob at Javascript, but I'm trying to implement something on my website where users can type a quantity, and the subtotal updates dynamically as they type.
For example: if items are 10 dollars each, and a user types 5 in the text field I would like it to show $50 next to the text box. Pretty simple multiplication, but I don't know how to do it with Javascript. I think onKeyPress somehow? Thanks!
Assuming the following HTML:
<input type="text" id="numberField"/>
<span id="result"></span>
JavaScript:
window.onload = function() {
var base = 10;
var numberField = document.getElementById('numberField');
numberField.onkeyup = numberField.onpaste = function() {
if(this.value.length == 0) {
document.getElementById('result').innerHTML = '';
return;
}
var number = parseInt(this.value);
if(isNaN(number)) return;
document.getElementById('result').innerHTML = number * base;
};
numberField.onkeyup(); //could just as easily have been onpaste();
};
Here's a working example.
You should handle 'onkeyup' and 'onpaste' events to ensure you capture changes by keyboard and via clipboard paste events.
<input id='myinput' />
<script>
var myinput = document.getElementById('myinput');
function changeHandler() {
// here, you can access the input value with 'myinput.value' or 'this.value'
}
myinput.onkeyup = myinput.onpaste = changeHandler;
</script>
Similarly, use getElementById and the element's innerHTML attribute to set the contents of an element when you want to show the result.

Categories

Resources