Only allow number to be entered once in input - javascript

Is there any way of using javascript/jquery to prevent a user entering the same number twice in an input box? The user can enter as many numbers as they want (one at a time), but I need to alert the user/take other action if they try to enter the same number a second time. I have tried creating an array:
function history() {
var numbers = [];
numbers.push(document.getElementById('inputBox').value);
}
and then running:
var n = document.getElementById('inputBox').value;
if ($.inArray(n, numbers)> -1) {
// alert, do something
}
but the new array ('numbers') never gets populated by the user input, so the if clause never fires.

Something like this, perhaps? I assume you are using jQuery because of the $.inArray in your code.
var numbers = [];
$('#inputBox').change(function () {
if ($.inArray($(this).val(), numbers)) {
// Alert the user/take other action
} else {
// Otherwise, add it to the array of numbers
numbers.push($(this).val());
}
});
It would be better if there was a button the user had to click to add the new number. Otherwise, it will be quite annoying.

It looks like your numbers variable is scoped to the history() function, so the numbers variable instanced that is being set is only accessibly by the history() function. This code will accomplish what you're trying to do without a global numbers variable and prevents any duplicate numbers from being entered by intercepting and canceling the key event.
$("#inputBox").on("keydown", function(e) {
var numbers = $(this).val();
var c = String.fromCharCode(e.keyCode);
return ~numbers.indexOf(c);
});

Related

Validate Multiple controls at once with most optimized way in javascript

I have multiple methods which validates and return Boolean value a control. what can be best way to write the logic so that it validates and highlights all invalid controls, doesn't submit form to server and in future I have to make least code change if new control is added.
Aprroach 1. And , OR logic operator will not give correct result
if ( (Method1(ctrl1) && Method2(ctrl2) && Method3(ctrl3)))
{ // not submit to server }
else //submit the form
Approach 2 - still change in logic will require if new control is
added for validation
var valid1 = Method1(ctrl1);
var valid2 = Method1(ctrl2);
var valid3 = Method1(ctrl3);
if(va1id1 && va1id2 && va1id3)
// not submit to server
else
// submit to server
Have an array called valid which contains the result of all validations.
var valid = [];
valid.push(Method1(ctrl1));
...
var entry = valid.reduce(function(validity,state){
return validity && state; //if any entry in the valid array is false the result will be false
},true);
if(entry){
//do something
}
else{
//do something else
}
If a new validation check has to be added you have to add one line to the code though: valid.push(Method1(ctrln));
The object oriented answer: have one class / object per "check". They all go into a list of some sort. The final checking works by iterating that list to call the same method there.
That only requires you to add a new class / object for each new check you need.

Javascript prompt alternative in Loop

So, instead of a prompt, I could use an <input type="text"> and a button to do stuff with the values of the input on button click, for example:
var x = [];
$('button').on('click', function(){
x.push($(input[type="text"]).val());
});
However, in a loop for example:
var y=0;
var z=[];
do {
z.push(prompt('input value'));
y++;
}
while (y<5);
The loop would prompt for a value, user inputs value, prompt assigns value to array, then the loop would prompt again until y reaches 5.
Instead of a prompt, I'd like to do this with my text field input and button. How can I get the loop to pause, wait for user to input text, and submit by clicking button, every time it reaches that part of the loop?
Edit: The pushing of 5 values into the array was just an example. Let's say I wanted to create a game where the loop would move up with an "up" and down with a "down" input. I want to be able to request user input during the loop, similar to how the prompt would do it, but without using prompts.
You don't. You completely change your logic, losing the loop entirely:
var z = [];
$('button').on('click', function() {
z.push($(input[type="text"]).val());
if (z.length === 5) {
// Do what you would have done after the end of the loop here
}
});
You've edited the question and commented below that what you do next might vary depending on the input. That's not a problem, you just apply the event-response model to your new requirement. For instance, you said
...Let's say I wanted to create a game where the loop would move up with an "up" and down with a "down" input.
Then:
$('button').on('click', function() {
switch ($(input[type="text"]).val().toLowerCase()) {
case "up":
// Do the "up" thing
break;
case "down":
// Do the "down" thing
break;
}
});
There are several different ways you might handle dispatching, not necessarily a switch. For instance:
var actions = {
up: function() {
// Do the "up" thing
},
down: function() {
// Do the "down" thing
}
};
$('button').on('click', function() {
var action = actions[$(input[type="text"]).val().toLowerCase();
if (action) {
action();
}
});
And so on. The key is that instead of working iteratively (I do this, I get that input, I do the next thing, I get more input), you're working reactively: I get input, I do something. That might require some kind of state management (remembering where you are) beyond what's shown above (the first example has state management: We check the length of z to see how many inputs we've collected).

Make parseFloat convert variables with commas into numbers

I'm trying to get parseFloat to convert a userInput (prompt) into a number.
For example:
var userInput = prompt("A number","5,000")
function parse_float(number) {
return parseFloat(number)
}
When userInput = 5,000, parse_Float(userInput) returns 5.
However, if the user was inputting a value to change something else (ie: make a bank deposit or withdrawl) Then I to work properly, parse.Float(userInput) needs to return 5000, not 5.
If anyone could tell me how to do this it would help me so much. Thanks in advance.
Your answer is close, but not quite right.
replace doesn't change the original string; it creates a new one. So you need to create a variable to hold the new string, and call parseFloat on that.
Here's the fixed code:
function parseFloatIgnoreCommas(number) {
var numberNoCommas = number.replace(/,/g, '');
return parseFloat(numberNoCommas);
}
I also renamed the function to parseFloatIgnoreCommas, which better describes what it does.
This is the function I use to scrub my user inputted numbers from a form. It handles anything a user may put in with a number like $ or just accidentally hitting a key.
I copied the following out of an object:
cleanInput : function(userValue){
//clean the user input and scrub out non numerals
var cleanValue = parseFloat(userValue.replace(/[^0-9\.]+/g,""));
return cleanValue;
},
To make it non-object just change the first line to cleanInput(){....
I have put together info from the comments to form a basic answer:
The answer seems to simply be to set parse_float to run :
number.replace(/,/g, "")
return parseFloat(number)
The complete code would look like this:
var userInput = prompt("A number","523,000,321,312,321")
function parse_float(number) {
number.replace(/,/g, "")
return parseFloat(number)
}
returns: 523000321312321

how to check that user can not input more than one decimal or dot in html web page

I have web page with input field i want that user can input number in that but number should not contain two decimals like 10.0.0 mean it can only enter .one time not two times any idea how we can fix this.
Presuming input element el is already assigned to a variable v.
if (1 < v.match(/\./g).length) {
alert("Multidots found");
}
function run(element) {
var regex = /\d*\.?\d?/g;
element.value = regex.exec(element.value);
}
call this function on keypress
You could handle the event of the keypress or keyup and check if the key pressed is a dot. If it is entered the first time, you could assign a boolean centinel to true, and cancel the keypress event for future dots.
Try using
var str = '10.0.0';
str.indexOf('.');
which gives how many times its contain in a string.

How can I stop isNaN from returning an error for a blank field?

EDIT:
Ok so I'm updating this question, to show what I've built as I've still not been able to fix this issue. Here is an image of what I've got. So as you can see,
When the user enters a value, the calculation (they are just percentage and total calculations are done "onkeyup". As you can see because of this they return "NaN". Is there a way for me to stop the field displaying a NaN and then subsequently only showing the total values?
I have thought about this and I could just get all the fields to calculate as soon as something is input into the final field? What do you think. Apologies to all those that had perviously answered my question, I am still trying to figure out the best approach, I'm just not as good with JavaScript as I am with HTML/CSS!!
You should try writing a checkNumber function that takes the entered value as its argument (rather than referring directly to each field inside the function). Something like this:
var checkNumber = function (testval) {
if ( isNaN(testval) ) {
alert('Bad!');
// clean up field? highlight in red? etc.
} else {
// call your calculation function
}
}
Then bind that function to the keyup event of each form field. There are a number of ways to do this. Look into addEventListener(), or the binding features of a framework like jQuery (.delegate() or .keyup(), e.g.).
Note that if you do bind the function to the event, you won't have to explicitly pass in the value argument. You should be able to work with a field's value within the function via this.value. So you'd have something like this:
var checkNumber = function () {
if ( isNaN( this.value ) ) {
alert('Bad!');
// clean up field? highlight in red? etc.
} else {
// call your calculation function
}
}
And then (with a naive binding approach by ID):
document.getElementById('id_of_a_field').addEventListener('keyup', checkNumber, true);
Can't you just initialize the text box with a default value, say 0?
Why don't you use 3 different functions or an argument to identify which of the inputs the user is pressing? If each of the inputs calls checkNumber(1), checkNumber(2) and checkNumber(3) you can only validate the input that the user is using instead of validating all 3 at the same time.
Alternatively you can use input validation and instead of an alert just return false to prevent the user from inputing invalid chars
How about use short-circuit evaluation with jsFiddle example
EDIT for parseFloat:
function checkNumber()
{
var sInput = parseFloat(document.getElementById('sInput').value || 0);
var dInput = parseFloat(document.getElementById('dInput').value || 0);
var pInput = parseFloat(document.getElementById('pInput').value || 0);
if (isNaN(sInput) || isNaN(dInput) || isNaN(pInput)) {
alert("You entered an invalid character. Please press 'Reset' and enter a number.");
}
}
So if pInput is undefined just use 0, but if the input has value then use that value.
SIDE NOTE: white space is actually a number, +' '; // 0

Categories