Format Numbers in JavaScript - javascript

I have a web page that allows a user to enter values into fields. When a user updates a field, I want to automatically update the total displayed to the user. Because the input fields are dynamically generated, I created a JavaScript function called "update". A sample of my code is shown here:
<input type="text" id="myField1" onchange="return update(this);" />
<input type="text" id="myField2" onchange="return update(this);" />
<span id="totalCount"></span>
var total = 0;
function update(e) {
var v = $(e).val();
if (parseInt(v) != NaN) {
total = total + v;
$("#totalCount").html(total);
}
return false;
}
When a user enters "2" into "myField1", "02" is displayed in the "totalCount" element. In reality, I would like to just display "2". How do I do this in JavaScript while taking into a account odd entries?
Thanks!

Since $(e).val() is a string, total + v is a string too. Use parseInt not just for the test but also when using the value:
var v = parseInt($(e).val(), 10);
if (!isNaN(v)) {
total = total + v;
$("#totalCount").html(total);
}

Related

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 do I increment the value of an input of type=number using jQuery?

I'm trying to increment the value of an input type="number" element using jQuery. However I currently have it so that every time I press the add button it appends 1 to the value so I get a value like 1111 etc etc...
I was able to do it fine when it was set to type=text but it was not ideal as I was trying to increment the values so all that was happening was the counter was being appended to the value of the input box. Output was like this 01 02 03 04.
Currently, I'm doing this:
HTML
<input type="number" class="qty" id="book-qty" disabled/>
<span class="add">ADD</span>
jQuery
var count = 0;
$('.minus').click(function () {
if (count - 1 >= 0) {
count = parseInt($(this).parent().find('#book-qty').val());
count = count - 1;
$(this).parent().find('#book-qty').val(count);
} else {
alert('Nothing to take away!');
}
});
$('.add').click(function () {
count = $(this).parent().find('#book-qty').val();
count = count + 1;
$(this).parent().find('#book-qty').val(count);
});
I have a JSFiddle I'm working on here:
https://jsfiddle.net/javacadabra/L1sLr921/
Does anyone know?
jsfiddle demo
you need to parse the value to an integer otherwise it get treated as a string so it will concatenate instead of add together.
count = parseInt($('#book-qty').val());
Also you need to specify a default value for your inputs like stated by Mex.
Set the default value to 0 with "value=0" on the input type=number.
Then use:
count = parseInt(count) + 1;
instead of:
count = count + 1;

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

Jquery - Adding Input value and another number together if checkbox is checked

Im creating a form where i want the user to fill out an amount, and then show at the bottom of the form. Then if there is a checkbox checked it adds 21 to the value within the input field so far i have this, but its not quite working.
http://jsfiddle.net/vePbV/
<label>Desired amount</label> <input name="tbDesiredAmount" type="number" id="tbDesiredAmount" min="50" />
<label>Include Apron?</label> <input id="cb_Apron" type="checkbox" name="cb_Apron" />
<p>Total: £<span id="total">0</span>.00</p>
$('#tbDesiredAmount').blur(function() {
var value = $('#tbDesiredAmount').val();
$("#total").empty().append(value);
});
$('#cb_Apron').blur(function() {
var value = $('#tbDesiredAmount').val();
var apron = 21;
var total = value + apron;
$("#total").empty().append(total);
});
So and example of what i want it to do.
Type 70 into "desired amount", show 70 in #total when you focus off the input field.
Check apron tickbox, adds 21 to the desired amount so displays 91 in #total
if you uncheck the apron checkbox, it will remove 21 from the figure in #total
if i change the desired amount, it will update the #total, this needs to work with the tickbox checked and the tickbox not checked.
Any help would be greatly appreciated as im rather stuck at the moment.
Try this Use parseInt()
var apron = 21;
$('#tbDesiredAmount').keyup(function () {
var value = $('#tbDesiredAmount').val();
if ($('#cb_Apron').is(':checked')) {
var total = parseInt(value) + parseInt(apron);
$("#total").empty().append(total);
} else {
$("#total").empty().append(value);
}
});
$('#cb_Apron').click(function () {
if ($(this).is(':checked')) {
var value = $('#tbDesiredAmount').val();
var total = parseInt(value) + parseInt(apron);
$("#total").empty().append(total);
} else {
var tot = parseInt($("#total").text()) - (parseInt(apron))
$("#total").empty().append(tot);
}
});
DEMO

calculation based on input field for a result on the fly

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?

Categories

Resources