I want spinner to display numbers properly - javascript

I have 2 questions:
Question 1: I have a spinner function and I have one slight problem with it. If a user types in 00000009 or 00021 in the spinner for example, if the user clicks away from the spinner, it will still display 00000009 or 00021 in the spinner. What I want is that if something like this happens, then what I want is that when the user clicks away, I want the spinner to display it as 9 or 21 rather than 00000009 or 00021. I don't know how to do this though. Does anyone know how to overcome this:
Question 2: If I used backspace to remove a number from a spinner and that is left with a blank spinner, what needs to be done so that if I click away from the spinner, the last number in the spinner re-appears in the spinner?
My main spinner function:
function Spinner(elem,min, max){
this.elem = elem;
this.elem.value = min;
this.min = min;
this.max = max;
this.timer;
this.speed = 150; //milliseconds between scroll values
var selfO = this;
this.elem.onkeyup = function(){
var regex = /^[0-9]*$/;
if(!regex.test(selfO.elem.value)){
selfO.elem.value = selfO.elem.value.substring(0,selfO.elem.value.length-1);
return;
}
selfO.validateValue();
}
this.validateValue = function(){
if(Number(selfO.elem.value) > selfO.max) {selfO.elem.value = selfO.max;}
if(Number(selfO.elem.value) < selfO.min) {selfO.elem.value = selfO.min;}
}
this.stopSpinning = function(){
clearTimeout(selfO.timer);
}
this.spinValue = function(dir){
selfO.elem.value = Number(selfO.elem.value) + dir;
selfO.validateValue();
selfO.timer = setTimeout(function(){selfO.spinValue(dir);},selfO.speed);
}
};
window.onload=function(){
//create the Spinner objects
var SpinnerHours = new Spinner(document.getElementById('txtHours'),0,23);
}

To return a number like 00000009 as 9 use parseInt();
alert( parseInt(000000009, 10) ); // returns 9
As pointed out by Jonathan Lonowski The second parameter is the radix.
The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.
If the radix parameter is omitted, JavaScript assumes the following:
If the string begins with "0x", the radix is 16 (hexadecimal)
If the string begins with "0", the radix is 8 (octal). This feature is deprecated
If the string begins with any other value, the radix is 10 (decimal)

//question 2 answer
var input='';
document.getElementById('inputName').onkeydown=function(e){
e = e || window.event;
keycode = e.keyCode || e.which;
if(keycode !== 8 || keycode !== 46){//backspace and delete keycodes
input=this.value;
}
}
//question 1 answer
document.getElementById('inputName').onblur=function(){
var a=this.value;
if(isNaN(a)){
this.value=input-0;
}
else{
this.value=a-0;
}
}
What this does is when a user is entering a number it saves the value unless the are pressing delete or backspace. Then when the input loses focus it checks and if there is not a valid number there it changes it to the saved value. Also the onblur get rid of any extra zeroes. Also, you will need to add more to the part that checks the input. For instance changing any non-numeric input to ''. In other words it isn't idiot proof.

Related

Hiding the 0 that shows when a user presses the AC button on my calculator

I've added an AC button to my JS calculator which resets the variables and displays 0 in the displayArea.
However when the user starts typing their first number the 0 stay's so it shows 03 instead of 3 etc - this doesn't impact the calculation.
I've tried to remove this using parseInt and an IF statement however it doesn't seem to work.
My best attempt so far is:
<p id="result-display"> </p>
let displayArea = document.getElementById('result-display');
else if (displayArea.innerHTML = 0) {
buttonNumber = Number(e.target.innerText);
displayValue = buttonNumber;
displayArea.innerHTML = parseInt(displayArea.innerHTML += displayValue);
}
If I change the 0 to a string e.g. '0' it works but then also stops the user entering multiple number values e.g. 56 would show as 5 etc.
My JSFiddle is: https://jsfiddle.net/mh85skxv/3/
Add the following line at the end of your calculate function:
displayArea.innerHTML = Number(displayArea.innerHTML);
This will convert the content of the displayArea to a number, eliminating any leading zero.
If you don't want the 0 to appear when pressing AC just replace this line:
displayArea.innerHTML = 0;
with this:
displayArea.innerHTML = '';
Then parse your number like this in order to avoid NaN:
Number(displayArea.innerHTML) || 0;
Not sure of the exact solution, but here's a few tips from your question and your Fiddle code:
else if (displayArea.innerHTML = 0) { can't work because you need == or ===. Using only the equal sign doesn't check the value of displayArea.innerHTML but assigns it to 0.
Also innerHTML is not usually equal to 0...maybe try innerHTML.length or something ?
On your fiddle code I notice that you use statements like return firstNumber = .... This is incorrect; instead, declare your variable firstNumber at the top, and for each switch case write something like:
firstNumber = //whatever you want
break; //this will ensure your code stops there
Hope this helps,

Restrict text input to number groups separate by a non-consecutive character

I've been doing a lot of searching, chopping and changing, but I'm...slightly lost, especially with regards to many of the regex examples I've been seeing.
This is what I want to do:
I have a text input field, size 32.
I want users to enter their telephone numbers in it, but I want them to enter a minimum of 10 numbers, separated by a single comma. Example:
E.g. 1
0123456789,0123456789 = right (first group is >=10 numbers, second group = >=10 numbers & groups are separated by a single comma, no spaces or other symbols)
E.g. 2
0123456789,,0123456789 = wrong (because there are 2 commas)
E.g. 3
0123456789,0123456789,0123456789 = right (same concept as E.g. 1, but with 3 groups)
I've got the following, but it does not limit the comma to 1 per 10 numbers, and it does not impose a minimum character count on the number group.
$(document).ready(function(){
$("#lastname").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && String.fromCharCode(e.which) != ','
&& (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
Preferably, I'd like to warn the user of where they are going wrong as well. For example, if they try to enter two commas, I'd like to specifically point that out in the error, or if they havent inserted enough numbers, i'd like to specifically point that out in the error. I'd also like to point out in the error when neither a number or a comma is inserted. I'd like to ensure that the tab, and F5 keys are not disabled on the keyboard as well. And very importantly, I'd like to specifically detect when the plus or addition key is used, and give a different error there. I think I'm asking for something a little complex and uninviting so sorry :/
The example code I provided above works pretty well across all browsers, but it doesn't have any of the minimum or maximum limits on anything I've alluded to above.
Any help would be appreciated.
As far as a regex that will check that the input is valid (1-3 phone numbers of exactly 10 digits, separated by single commas), you can do this:
^\d{10}(,\d{10}){0,2}$
Try like the below snippet without Regex
var errrorMessage = '';
function validateLength (no) {
if(!no.length == 10) {
return false;
}
return true;
}
function validatePhoneNumbers (currentString, splitBy) {
if(currentString) {
var isValid = true,
currentList = currentString.split(splitBy);
// If there is only one email / some other separated strings, Trim and Return.
if(currentList.length == 1) {
errrorMessage = 'Invalid Length in Item: 1';
if(validateLength( currentString.trim() )) isValid = false;
}
else if(currentList.length > 1) {
// Iterating mainly to trim and validate.
for (var i = 0; i < currentList.length; i++) {
var listItem = currentList[i].trim();
if( validateLength(listItem ) ) {
isValid = false;
errrorMessage = 'Invalid Length in Item:' + i
break;
}
// else if for some other validation.
}
}
}
return isValid;
}
validatePhoneNumbers( $("#lastname").val() );

Don't allow the user to enter numbers greater than 12

I have an HTML textbox as:
<input style="width: 13%; height: 25%" name="txthour" id="txthour" onkeypress="return isNumberKey(event)">
I want user to stop if they enter a number greater than 12.
When the user has entered 1, I don't want to them to enter the number 3, this will prevent the number becoming 13 (which is greater than 12).
I am dong this in Javascript as:
function isNumberKey(e) {
if (isNaN($("#txthour").val()))
{
alert("Enter only numbers");
}
if ($("#txthour").val() > 12) {
e.cancel;
}
}
But it's not cancelling the text if it enters 13.
Your first problem with your code is that you are binding it on keypress. That means $("#txthour").val() will not be updated before your event.
You need to know which character the user has pressed. There is a function for that: String.fromCharCode();.
To get the current character, you can use this:
var currentChar = parseInt(String.fromCharCode(e.keyCode), 10);
then you need to check if it is a number:
if(!isNaN(currentChar))
Then you need to concatenate that character to your input:
var nextValue = $("#txthour").val() + currentChar; //It's a string concatenation, not an addition
Parse the new value and check if it's less than or equal to 12. If all of these condition matches, return true.
Final code :
function isNumberKey(e) {
var currentChar = parseInt(String.fromCharCode(e.keyCode), 10);
if(!isNaN(currentChar)){
var nextValue = $("#txthour").val() + currentChar; //It's a string concatenation, not an addition
if(parseInt(nextValue, 10) <= 12) return true;
}
return false;
}
http://jsfiddle.net/6X9Yq/
Edit
To allow the press of the enter key, you need to check if the keycode is 13 :
function isNumberKey(e) {
if(e.keyCode === 13) return true;
var currentChar = parseInt(String.fromCharCode(e.keyCode), 10);
if(!isNaN(currentChar)){
var nextValue = $("#txthour").val() + currentChar; //It's a string concatenation, not an addition
if(parseInt(nextValue, 10) <= 12) return true;
}
return false;
}
Try this instead:
function isNumberKey(e)
{
var exString = $('#txthour').val();
var newString = exString + String.fromCharCode(e.keyCode);
if (isNaN(newString))
{
alert("Enter only numbers");
}
if (newString > 12)
{
e.preventDefault();
}
}
The reason your original code doesn't work is because when the keydown event is called, the value of the text box hasn't been set yet. The code above figures out what the value will be based on your keystroke, and then checks to see if the future value will be > 12. If so, then the preventDefault() call cancels your input.
jQuery solution that:
1) Checks to make sure the user only inputs numbers.
2) Makes sure the number entered is 12 or lower.
3) Alerts the user based on the criteria they're not meeting, and clears the input field.
4) Also accounts for a user pasting something into the field.
$('#txthour').on('paste input', function () {
var number = $(this).val()
if (isNaN(number)) {
alert("Enter only numbers.");
$(this).val('');
}
if (number > 12) {
alert("Value entered must be 12 or lower.");
$(this).val('');
}
});
FIDDLE
$( "#txthour" ).keyup(function() {
if($( "#txthour" ).val() > 12)
{
$( "#txthour" ).val("12");
}
});
http://jsfiddle.net/5tjdL/
The problem:
When the user types a value and you are listening to the onkeypress event, you want to be able to see what the resulting value would be so that you can compare that new value to some other value and then determine if you want to block that input via event.preventDefault() method.
Heres my solution:
1) calculate the "true" new value(now unlike most answers that were previously written that make a huge erroneous assumption "My user will only type a value at the very end of the input field"), I will take into consideration the fact that a user can actually select existing input and overwrite it...ie [before key press] inputField = "12345", user selects "12345" and presses the key for "5", so that would mean that the new value is "5", or if the user selected "234" and pressed the key for "5", the resulting value would be "155".
2) once you have the final "true" value, you can now use the isNaN() method to test if the final value is a valid number or you could just pass the final value to your own method to make whatever comparison you need and decide stop the event by calling event.preventDefault() method. here's a sample code for achieving that.
$(document).keypress(function(event)
{
//this is just a container object for readability purposes
let eventData = {
element: null,
userinput: "",
fieldname: "",
fieldValue: null,
selectionStart: -1,
selectionEnd: -1
}
eventData.fieldName = event.target.id;
eventData.element = document.getElementById(eventData.fieldName);
eventData.fieldValue = element.value; //holds the value before modification
eventData.input = String.fromCharCode(event.keyCode); //what ever the user typed!
eventData.selectionStart = event.target.selectionStart;//this records
eventData.selectionEnd = event.target.selectionEnd;//the user selection if any
let finalValue = getFinalValue(eventData);
if(!isNaN(finalValue)){
//the final value is a number and can be compared to another number!
alert("we have a number! you may proceed");
}else {
//stop right there mister!
alert("You shall not pass!");
event.preventDefault();//user input was blocked!
}
}); // this here marks the end of the onkeypress method,
// and now getFinalValue(eventData) method below...
function getFinalValue(eventData){
let finalValue = eventData.fieldValue.substring(0,eventData.selectionStart) +
eventData.input + eventData.fieldValue.substring(eventData.selectionEnd);
return finalValue;
}//end of the getFinalValue() method

using Javascript to force number precision on event Onkeypressed in textbox

what i need is to force user while they are typing in a textbox
-
the maximum number they can put is 16
if they press . they can put additional 2 digits after the dots
so what i have done so far is
<asp:TextBox ID="textbox" runat="server" Width="200" onkeypress="validateCurrencyX(this,7, 2);" >0.00</asp:TextBox>
the javascript code is
function validateCurrencyX(sender,prefix, suffix){
var something = document.getElementById('textbox').value;
var valueArr = something.split('.');
if (valueArr[1]!= null && valueArr[1].length > suffix-1)
event.returnValue = false;
if (valueArr[0].length > prefix-1)
event.returnValue = false;
}
anyway my code has problems that
- when i select the whole text, or some part of the text, and press something, it doesn't change anything
is there any ordinary way they do this ? i'm quite new to both javascript and asp.net
thank you for attention
Since you are new to both javascript and .net, it would be best that you not try to reinvent the wheel.
If you are open to using jQuery, take a look at NumberFormatter
$(".amt").blur(function(){
$(this).format({format:"#,###,###,###,###,###.00", locale:"us"});
});
This does what you want it to:
<asp:TextBox ID="textbox" runat="server" Width="200" oninput="validateCurrencyX(this,7, 2);" onkeydown="validateCurrencyX(this,7, 2);" >0.00</asp:TextBox>
JavaScript:
var validateCurrencyX = (function() {
// Closure for local oldVal variable
var oldVal = 0;
return function validateCurrencyX(sender, prefix, suffix) {
setTimeout(function() {
// Convert to number
var val = sender.value * 1,
// Get decimals
dec = sender.value.split('.')[1];
if(
val != val // NaN
|| val > 16
|| val < 0
|| dec && dec.length > suffix // check number of decimals
) {
// If the new input doesn't fit the criteria, revert to the old input.
sender.value = oldVal;
} else {
if(Math.floor(val) != 0 && sender.value.charAt(0) == '0') {
// If it's a number >= 1, remove leading '0's.
sender.value = sender.value.replace(/^0+/, '');
}
// Value is good. Save it in case we need to revert later.
oldVal = sender.value;
}
}, 0);
};
})();
Here's a working example: http://jsfiddle.net/6HUUT/4/
The key to getting a user-friendly real-time text validator is to (1) use onkeydown / oninput not onkeypress because onkeypress doesn't fire for things like paste and delete, and (2) use a setTimeout with interval 0 to check what the user actually inputs and change it after it is updated in the textbox, rather than trying to prevent them from inputting it at the outset. Again, this helps with things like paste and delete, and also inserting characters in places other than the beginning, and generally makes your life easier. The idea is just to let the user make changes, and then check them to make sure they're ok.
Note, the use of onkeydown along with oninput is used for legacy browsers. input is sufficient for modern browsers, but older browsers (circa IE8) don't support it.
This is without using javascript since you have said- is there any ordinary way they do this ? So just have a look at this:
1) the maximum number they can put is 16: for this you have the maxlength property of textbox. Set it to 16
2) This piece of code will restrict your user in entering only 2 digits after the decimal in your textbox.
//In key press event of your TextBox:
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
if (!char.IsControl(e.KeyChar))
{
TextBox tt = (TextBox)sender;
if (tt.Text.IndexOf('.') > -1 && tt.Text.Substring(tt.Text.IndexOf('.')).Length >= 3)
{
e.Handled = true;
}
}

How to check If a Tel: area code is correct using jquery?

Hy
I need to check if the given phone area code is correct.
i created a input field, user can insert a tel area code like 0044 oder 0090 and so on.
I restricted the input field to 4 chars.
I need to check after the 4 chars are entered if the area code is correct.
What it should do.
After entering 4 number, the script should check the following things.
Does the entered number equals something like "00{number 2 digit only}" if it doesnt alert("please enter correct tel areacode");
I hope i could explain my problem clear.
How can i do it with javascript or jquery?
Is "0000" a valid area code? It has "00" followed by two digits... but I assume the codes are 00 then a number 10 or higher.
$('input.phone').keyup( function(){
var num = $(this).val(), i = parseInt(num, 10), valid = true;
if(num.length==4 && (i<9 || i>99) ){
//phone number is invalid
}
});
But I think that blur event will be more useful here, because the above function wouldn't notify the user if he typed only three digits. Notification will appear as soon as the focus is moved aout of the input box, not as soon as the fourth digit was typed. So my proposition is:
$('input.phone').blur( function(){
var num = $(this).val(), i = parseInt(num, 10), valid = true;
if(num.length != 4 || i<9 || i>99 ){
//phone number is invalid, notify the user
}
});
edit: I thought you're validating some kind of area codes specific to your coutry. If you want to validate international calling codes you may wish to look at this list: http://en.wikipedia.org/wiki/List_of_country_calling_codes - there are many +XXX (or 00XXX) numbers and these won't fit into your 4 characters long input. And many numers aren't in +XX (00XX) format, like +1 (001) for USA. I think you should just check if it's + or 00 followed by at least one digit other than zero and let it in.
/^(\+|00)[1-9]/.test( input.value );
Something like this should work:
$('#field').keyup(function() {
var value = $(this).val();
// Restrict length to 4 characters
if(value.length > 4) {
value = value.substring(0, 3);
$(this).val(value);
}
// Test is value equals to "00{number 2 digit only}"
if(/00\d{2}/.test(value)) {
// Is valid
} else {
// Not valid
}
});
I'd avoid using alert on the not valid part, as that would give the user an alert box every time he presses a key.

Categories

Resources