Allowing user to click only one "." - javascript

I am trying to implement a simple javascript-html calculator. What i want to do is,typing only one '.' by the user. How can i control this ? Here is the code that i tried.
I can already find the number of '.' but i'am confused now also this replaceAll function is not replacing '.' with empty string.
String.prototype.replaceAll = function(search, replace)
{
//if replace is null, return original string otherwise it will
//replace search string with 'undefined'.
if(!replace)
return this;
return this.replace(new RegExp('[' + search + ']', 'g'), replace);
};
function calculate(){
var value = document.calculator.text.value;
var valueArray = value.split("");
var arrayLenght = valueArray.length;
var character = ".";
var charCount = 0;
for(i=0;i<arrayLenght;i++){
if (valueArray[i]===character) {
charCount += 1;
}
}
if(charCount>1){
var newValue=value.replaceAll(".","");
alert(newValue);
}
}

I recently accomplished this with the following code. This sat in a function that was triggered for each keypress on the field. It might be a bit messy and I'm sure there's a better way, but it works. It also allows someone to enter a "." if they have one selected, since it would replace that selected one:
// Function to verify number
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
// Function called (below) to get text if it is selected
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text;
}
// jQuery function on keypress for the textbox
$(".textbox").on("keypress", function (e) {
var fieldVal = $(this).val();
if (e.keyCode == 9) return true; // tab
var keyPressed = String.fromCharCode(e.keyCode);
if (keyPressed == "." && ((fieldVal.indexOf(".") == -1) || getSelectionText().indexOf(".") > 0)) return true; // decimal places, only allow one
return (isNumber(keyPressed));
});
EDIT: I should mention, the isNumber() function also checks to verify that the end result is a number. I can post that if you'd like also.
EDIT 2: Modified code block to add the isNumber() function.

Your (main) problem is this test :
if(!replace)
When replace is "", !"" is true.
Change the test to
if (replace==null)
(it works for both undefined and null)
But I don't really see why you need to define a replaceAll function when you seem to want
var newValue=value.replace(/\./g,"");
EDIT : If what you want is to replace all dots apart the first one you can do
var i=0, newValue=value.replace(/\./g, function(){ return i++ ? "," : "." });
(you don't need to count before that, and i will be the count of dots)

Related

Check if key is in array-JavaScript

I have this JavaScript code
function checkTextField() {
var textVal = document.getElementById("textfield").value;
if (textVal == '', textfield.value.length <= 31)
{
alert('Wrong Key-Code. Key-Code must have 32 characters!');
}
else //Its all about how to decrypt a database file called ,,Salam Horia Allah,,!(good luck hackers)
{
{
var text = document.getElementById("textfield").value;
if (text ==
"3e6898f92134d05408dfed30b268d9d6",
"fa0f82cc02a6cdc35072ee5ce2b0c379",
"6a1df566fcaabca717aa1b81c3e0bd31",
"dc0beea186c5f5c2110bedbeccc5a7aa",
"1a317dbc4587268809b67179c391a5da9debb6261e3a3bcf7e6cd2b34356fc40",
"08a8c9750b3d184e6450b98fa90208bbd6c07171c0cce929bc52be1fdb44b09c",
"ac8ce3072f41269be4626539650bb1981c2939db0ffd576f240d06b0b7470c11",
"23a306626c5e9f83d8ce6012f9209fb8f3adcc1a098ffbfafd3c7965ed2c30a6",
"teBy%udu#uMuGyZe4uTyHeNa5yLy6avyTumypy8uHaGujytaWy",
"SezyDuXaquneguzuLatydy7e2ygu4y5e7uqe3e6uheVuVeSumu"
)
{
location.href = "http://79.115.70.31:8521/InWork/"
}
else {
alert("Wrong Key")
}
}
}
}
and here is what happen:
i have a textbox and a button,when i insert a key from if (text ==
"3e6898f92134d05408dfed30b268d9d6",
"fa0f82cc02a6cdc35072ee5ce2b0c379",
"6a1df566fcaabca717aa1b81c3e0bd31",
"dc0beea186c5f5c2110bedbeccc5a7aa",
And when someone press that button, I want that script to check if one of that keys are in text field, if is true the request will send to another page, if is not true, show an alert.
But my problem is, whatever I write in that textbox it send me to that page, also I got an alert if textbox have <31 characters.
The comma operator works inside of an if clause, but it takes the last value, not a logical OR, which is here required.
(An input returns always a string and if empty, the string length is zero. A check for emptiness and a check for a length which is smaller than a value is superfluous, because the length check includes a zero length as well.)
if (textVal == '' || textfield.value.length <= 31)
// ^^
Beside that, I suggest to use an array for the valid keys for checking and check only if the value is in the array, then proceed or give an alert.
Another point is to assign the value of the input only once and use it in the whole function with the variable. Do not use a mixed style with a variable and document.getElementById("textfield").value together.
function checkTextField() {
var keys = ["3e6898f92134d05408dfed30b268d9d6", "fa0f82cc02a6cdc35072ee5ce2b0c379", "6a1df566fcaabca717aa1b81c3e0bd31", "dc0beea186c5f5c2110bedbeccc5a7aa", "1a317dbc4587268809b67179c391a5da9debb6261e3a3bcf7e6cd2b34356fc40", "08a8c9750b3d184e6450b98fa90208bbd6c07171c0cce929bc52be1fdb44b09c", "ac8ce3072f41269be4626539650bb1981c2939db0ffd576f240d06b0b7470c11", "23a306626c5e9f83d8ce6012f9209fb8f3adcc1a098ffbfafd3c7965ed2c30a6", "teBy%udu#uMuGyZe4uTyHeNa5yLy6avyTumypy8uHaGujytaWy", "SezyDuXaquneguzuLatydy7e2ygu4y5e7uqe3e6uheVuVeSumu"],
text = document.getElementById("textfield").value;
if (keys.indexOf(text) !== -1) {
location.href = "http://79.115.70.31:8521/InWork/";
} else {
alert("Wrong Key");
}
}
Well you need to compare you tex with each key available so
function checkTextField() {
var textVal = document.getElementById("textfield").value;
var yourKeys =[ "3e6898f92134d05408dfed30b268d9d6",
"fa0f82cc02a6cdc35072ee5ce2b0c379",
"6a1df566fcaabca717aa1b81c3e0bd31",
"dc0beea186c5f5c2110bedbeccc5a7aa",
"1a317dbc4587268809b67179c391a5da9debb6261e3a3bcf7e6cd2b34356fc40",
"08a8c9750b3d184e6450b98fa90208bbd6c07171c0cce929bc52be1fdb44b09c",
"ac8ce3072f41269be4626539650bb1981c2939db0ffd576f240d06b0b7470c11",
"23a306626c5e9f83d8ce6012f9209fb8f3adcc1a098ffbfafd3c7965ed2c30a6",
"teBy%udu#uMuGyZe4uTyHeNa5yLy6avyTumypy8uHaGujytaWy",
"SezyDuXaquneguzuLatydy7e2ygu4y5e7uqe3e6uheVuVeSumu"];
if (textVal == '', textfield.value.length <= 31)
alert('Wrong Key-Code. Key-Code must have 32 characters!');
else {
var text = document.getElementById("textfield").value;
var i = yourKeys.length;
while(i--){
if(text == yourKeys[i] )
location.href = "http://79.115.70.31:8521/InWork/"
else
alert("Wrong Key")
}
}
}

Delete a group of characters when backspace is pressed (Javascript)

I have a textarea that contains new lines initialized by a number and a period:
<textarea autoFocus id="text-area"wrap="hard"
defaultValue ={this.state.textAreaVal} onKeyUp={this._editTextArea}/>
To illustrate this:
Line 1
Line 2
Line 3
I have a function that is called onKeyDown to check if the keycode is a backspace:
_editTextArea: function(event) {
var key = event.keyCode;
if (key == 8) {
//remove the whole line if the previous characters are a number followed by a period and then a space
} else {
return true;
}
},
My goal here is to delete the number and period with one backspace (how its done in microsoft word, imagine having an ordered list when you get to the bulletpoint or number or roman numeral and you press backspace, it not only deletes the whole list item but also it returns you to the previous list item's last char.
How can I accomplish this?
Try this, should give you enough to go on.
<p id="demo"></p>
<script>
function myFunction() {
var str = "Hello world! 12.";
while (str.substring(str.length-1) == "." || isNumber(str.substring(str.length-1)))
{
str = str.substring(0,str.length-1)
}
document.getElementById("demo").innerHTML = str;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
</script>
I don't know exactly what you want but this maybe could help you:
$('textarea').keyup(function (e) {
if (e.keyCode == 8) {
e.preventDefault();
var lines = $('textarea').val().split('\n');
lines.splice(this.value.substr(0, this.selectionStart).split("\n").length-1, 1);
$('textarea').val(lines.join("\n"));
}
})
You can try it here:
https://jsfiddle.net/swnhe2f0/1/

Numeric Fields on HTML elements

I have been trying to allow numeric field and one decimal point in my Grid.Its work fine when its suitable for input box.
when i am calling onKeyPress the script work fine for "input box" rather than on "Div element"
In "Div element",when i am supposed to use this .It allow to access only for number rather Alphabet
hence,while coming to "decimal place" its not working as it should.[ It's allowing many Dot's]
<script>
function getKey(e)
{
if (window.event)
return window.event.keyCode;
else if (e)
return e.which;
else
return null;
}
function restrictChars(e, obj)
{
var CHAR_AFTER_DP = 2; // number of decimal places
var validList = "0123456789."; // allowed characters in field
var key, keyChar;
key = getKey(e);
if (key == null) return true;
// control keys
// null, backspace, tab, carriage return, escape
if ( key==0 || key==8 || key==9 || key==13 || key==27 )
return true;
// get character
keyChar = String.fromCharCode(key);
// check valid characters
if (validList.indexOf(keyChar) != -1)
{
// check for existing decimal point
var dp = 0;
if( (dp = obj.value.indexOf( ".")) > -1)
{
if( keyChar == ".")
return false; // only one allowed
else
{
// room for more after decimal point?
if( obj.value.length - dp <= CHAR_AFTER_DP)
return true;
}
}
else return true;
}
// not a valid character
return false;
}
</script>
<div onKeyPress="return restrictChars(event, this)">
Any Ideas how we could achieve it
For an <input>, it is required to check the value attribute, hence why obj.value is used in your code above. A div element doesn't have a value attribute. You have to check it's innerHTML (mdn docs). If you replace all instances of obj.value with obj.innerHTML, your code should work.
You need to use jQuery keypress() method to handle this right:
$("#d input").keypress(function(event){
return restrictChars(event);
});
See the working fiddle:
http://fiddle.jshell.net/ePvJ8/1/

How to detect that a space was backspaced or deleted

I need to find a way to detect if a space was deleted or backspaced, and run a function if that is the case. I am working on this in JavaScript / jQuery.
I know I can get the delete or backspace key press by using:
$(this).keyup(function(event) {
event.keyCode
However, I do not know how to tell if the delete or backspace command removed a space?
Very appreciative for any suggestions.
See here: http://jsfiddle.net/Txseh/
(function(){
var currentWhitespaceCount;
$("input").keyup(function(e){
var newCount = ($(this).val().match(/\s/g) || []).length;
if (newCount < currentWhitespaceCount)
alert("You removed one or more spaces, fool.");
currentWhitespaceCount = newCount;
});
})();​
It tracks the current number of whitespace characters in the input, and if ever the number goes down, it alerts(or does whatever you want).
Cache the value beforehand (set a value on keypress) and compare with the value after keypress. That is the only way to know with certainty that one or more spaces has been removed. Any checking of keys relies on you being able to work out what possible keys could achieve the removal of a space, and will likely leave holes.
As an example, selecting the final letter of a word and the space following it, if we press the last letter it will remove the space. But the key pressed is not backspace or delete.
Bind to the keydown and compare the value from before and after to see if it reduced in size.
$(input).keydown(function(){
var currVal = this.value, self = this;
setTimeout(function(){
if ( currVal.length > self.value.length ) {
console.log(currVal.length - self.value.length + " characters have been removed.");
}
},0);
});
http://jsfiddle.net/ymhjA/1/
Updated sample:
$("input").keydown(function() {
var currVal = this.value,
self = this;
setTimeout(function() {
if (currVal.length - self.value.length === 1) {
var origVal = $.grep(currVal.split(""),function(val){
return val === " ";
});
var newVal = $.grep(self.value.split(""),function(val){
return val === " ";
});
if ( origVal.length != newVal.length ) {
console.log("a space was removed");
}
}
}, 0);
});​
http://jsfiddle.net/ymhjA/4/
actually here is my code http://jsbin.com/atuwez/3/edit
var input = $('#input'),
afterLength,
beforeLength;
input.on({
'keydown': function () {
beforeLength = input.val().split(/\s/).length;
},
'keyup': function(event) {
var key = event.keyCode || event.charCode;
if( key == 8 || key == 46 ) {
afterLength = input.val().split(/\s/).length;
console.log(beforeLength == afterLength);
}
}
});

javascript validation to check # at start of user input: not email validation

I have to check whether a form field contains '#' at start of user input & is it contains it at all. It works fine for checking if its at start of the string. But when I add checking whether input contains '#' at all or not. It fails. Here is my code
function email_valid(field)
{
var apos=field.update.value;
apos=apos.indexOf('#');
if (apos>0 ||((apos.contains('#')== 'FALSE')))
{ alert('plz enter valid input');
return false;
}
else
{ return true; }
}
EDIT
This function in this form is checking both if # is at 1st place & 2ndly is it in the input at all or not.
function #_valid(field)
{
var ref=field.update.value;// I needed ref 4 other things
var apos=ref.indexOf('#');
if (apos>=0 )
{
if (apos==0)
{
return true;
}
else { field.t_update3.value="";
alert('plz enter a valid refernce');
return false;
}
}
else { field.t_update3.value="";
alert('plz enter a valid refernce');
return false;
} }
Consider:
var apos = value.indexOf('#');
if (apos >= 0) {
// was found in string, somewhere
if (apos == 0) {
// was at start
} else {
// was elsewhere
}
} else {
// not in string
}
and
var apos = value.indexOf('#');
if (apos == 0) {
// was at start
} else if (apos > 0) {
// was elsewhere
} else {
// not in string
}
Why not just
if (apos !== 0) { /* error; */ }
The "apos" value will be the numeric value zero when your input is (as I understand it) valid, and either -1 or greater than 0 when invalid.
This seems like a strange thing to make a user of your site do, but whatever. (If it's not there at all, and it must be there to be valid, why can't you just add the "#" for the user?)
You can just check to make sure that apos is greater than -1. Javascript's indexOf() will return the current index of the character you're looking for and -1 if it's not in the string.
edit Misread a bit. Also make sure that it's not equal to 0, so that it's not at the beginning of the string.
function email_valid(field)
{
var fieldValue =field.update.value;
var apos = apos.indexOf('#');
if (apos > 0 || apos < 0)//could also use apos !== 0
{ alert('plz enter valid input');
return false;
}
else
{ return true; }
}
apos is the value returned by indexOf, it will be -1 if there is no # in the user input. It will be 0 if it is the first character. It will be greater than 0 if the user input contains an # . JavaScript has no contains method on a String.
Try:
function email_valid(field) {
//var apos=field.update.value;
var apos = field;
//apos=apos.indexOf('#');
apos = apos.indexOf('#');
if( (apos < 0) ) {
//alert('plz enter valid input');
alert('false');
} else {
alert('true');
}
}
email_valid('blah');
Checks for # anywhere. Or, if you want to check for # just at the beginning, change if( (apos < 0) ) { to if( (apos == 0) ) {. Or, if you want to make sure it's not at the beginning, then if( (apos > 0) ) {.
apos will be -1 if the string was not found. So your code should be as follows:
function email_valid(field)
{
var apos=field.value;
apos=apos.indexOf('#');
if (apos<=0) // handles '#' at the beginning and not in string at all.
{
alert('plz enter valid input');
return false;
}
else
{ return true; }
}
I also changed your initial assignment to remove the .update portion as that would cause it to fail when field is a reference to an input.
In the second if condition, apos is a number, not a string.
You're trying to write
if (field.update.value.charAt(0) == '#' && field.update.value.indexOf('#', 1) < 0)
Learn about Regular expressions if you haven't already. Then lookup Javascript's String#match. There is no need to find wether the input starts with an "#" as if it contains an "#" that will also return true if the "#" is at the start of the string.
Also, for free, return true and return false are generally bad style. Just return the thing you passed to if (that evaluates to a boolean).
All in all:
function validate_input(str) {
return str.match(/#/);
}
I reccomend passing the function a string (field.value or some-such) rather than the field itself as it makes it more generic.
Update: revised answer based on comments. code below will only return true if the value contains an "#" symbol at the first character.
If this is a JavaScript question, then this should be fine.
function email_valid(field){
var apos=field.update.value;
if(apos.indexOf('#') != 0){
alert('plz enter valid input');
return false;
} else {
//field contains an '#' at the first position (index zero)
return true;
}
}
That said, your parameter "field" if it actually refers to an input field element, should only require this code to get the value (e.g. I'm not sure where the ".update" bit comes into play)
var apos = field.value;
I would also rename this function if it isn't doing "email validation" to something a little more appropriately named.

Categories