onkeyup regex for validating numbers - html

I have below function which is used onkeyup for an input field. I want to allow users to enter numbers like 1 or -1 i.e positive or negative integers(no decimals) only. The regex i have used doesn't allow negative sign in the beginning. Tried different things and also looked up other questions but couldn't come with the correct one. Is there a better way to do it? Any help is much appreciated
function onlynumbers ()
{var text1 = document.getElementById("box1");
var numregex = /[^0-9]/gi
if (numregex.test(text1.value))
{
text1.value=text1.value.replace(numregex,"");
}
}

You can use this one that matches the hyphen only when it isn't at the start of the string:
var numregex = /[^0-9-]|(?!^)-/g;

This regex will allow for whole numbers and negative whole numbers!
^-?[0-9]\d*$

Related

Razor: Display procentage

I thought there would be an easy solution but I didnt succeed in finding anything that worked!
var squatPro = sumTotalSquatWeight/sumTotalVolume;
It's basically just this line, I don't know how to make it to decimal, since the result now is just 0 when the numbers are 9120/14895 = 0,61.
Adding * 100 at the end of the code gave 0 as well so that wasn't a solution!
(I'm not using MVC)
You may need to cast the numerator to a decimal:
var squatPro = (decimal)sumTotalSquatWeight / sumTotalVolume;
And if you want to round to 2 decimal places you can use something like this:
#squatPro.ToString("0.##")
Or if you need it as a percentage you can use this:
#(string.Format("{0:P}", squatPro))

Using JSON.stringify but SSJS variant in XPages

for an application I am building an administration panel where a power user should be able to check the JSON structure of a selected object.
I would like to display the JSON object in a computed text field but display/format it nicely so it is better human readable, something similar as in pretty print.
Is there any function I could use in SSJS that results in something similar so I can use display json nicely in computed text / editable fields?
Use stringify's third parameter "space":
JSON.stringify(yourObject, null, ' ');
space
A String or Number object that's used to insert white
space into the output JSON string for readability purposes. If this is
a Number, it indicates the number of space characters to use as white
space; this number is capped at 10 if it's larger than that. Values
less than 1 indicate that no space should be used. If this is a
String, the string (or the first 10 characters of the string, if it's
longer than that) is used as white space. If this parameter is not
provided (or is null), no white space is used.
As XPages doesn't support JSON.stringify yet you can include JSON's definition as SSJS resource and use it.
As Knut points out, you can certainly add json2.js to XPages; I've previously used an implementation as Marky Roden's post outlines. This is probably the "safest" way of doing so, from the SSJS side of things.
It does ignore the included fromJson and toJson SSJS methods provided out of the box in XPages. While imperfect, they are functional, especially with the inclusion of Tommy Valand's fix snippet. Be advised, using Tommy's fix does wrap responses to ensure a proper JS object can be parsed by shoving an Array into an object with a values property for the array; so no direct pulling of an Array only.
Additionally, I believe it would be useful to point out that a bean, providing a convenience method or two as wrappers to use either the com.ibm.commons.util.io.json methods to abstract the conversion method, or switching in something like Google GSON, might be more powerful and unified, based on your style of development.
Knut, Eric, I came so far myself already.
function prettyPrint(id) {
var ugly = dojo.byId(id).value;
var obj = $.parseJSON( "[" + ugly + "]" );
var pretty = JSON.stringify(obj, undefined, 4);
dojo.byId(id).innerHTML = pretty;
}
and I call it e.g.
var name = x$('#{id:input-currentObjectCollectionFiltered}').attr("name");
prettyPrint(name);
I tried to make use the x$ function but was not able to make the ID dynamic there e.g.
var ugly = x$('#{id:" + id + "}').val();
not sure why. would be nicer if I just would call prettyPrint('input-currentObjectCollectionFiltered'); and the function would figure it out.
Instead of dojo.byId(id).value I tried:
var ugly=$("#" + id).val();
but things returns and undefined object: I thought jquery would be smarter to work with dynamic id's.
anyway stringify works just fine.

Restricting input text to numbers only

Is there a way to restrict text to nubmers only in an input textfield?
I tried using:
myInputText.restrict = "0-9";
But it had no effect. Are there any other solutions?
myInputText.restrict = "0-9\\-\\^\\\\";
Try this, this should work.
[EDIT: My method described below is an alternative to .restrict, and can theoretically allow for much finer control.]
Yes, you can, quite quickly. We're going to combine a Regex and an event listener.
First off, you're going to need to set up an event listener on the text box. I'll call the input box txtInput, for the sake of conversation. This will point to a function we'll write called validate();
txtInput.addEventListener(KeyboardEvent.KEY_DOWN, validate);
Now, we need to create our function.
function validate(evt:KeyboardEvent):void
{
var currentString:String = txtInput.text; //It is usually easier to work with the textInput contents as a string.
var numbersRegex:RegExp = /^\d*$/; //A regular expression accepting zero or more numbers ONLY.
var invalidRegex:RegExp = /\D+/; //A regular expression accepting one or more NON-numbers.
if(numbersRegex.test(currentString) == false) //Run the test. If it returns false...
{
currentString = currentString.replace(invalidRegex, ""); //Removes all non-numbers.
}
//Else, we do nothing.
txtInput.text = currentString; //Put the updated string back into the input box.
}
(Granted, that code is untested, but it should more or less work.)
The logic going on here: The user enters a character into the box. The event listener fires as soon as the key is pressed. If the string isn't 100% numbers, then the string is searched for all non-number characters, and those characters are removed.
EDIT AS REQUESTED: Also, make sure you don't have conflicting instance names. If you have two input boxes with the same name, Flash may be looking at the wrong one.
txtInput.text = "Sample text." should throw a compiler error if there's a duplicate, or in the worst case, show you which input box you ARE affecting.

Removing commas from multidimensional arrays

I'm having a bit of trouble removing commas from an array when I go to write it to a cell in google spreadsheets. array.join(''); doesn't seem to do the trick. I would appreciate any help. Also, anchor[i][j].join('') returns an error.
Here is a bit of code:
anchor[i][j].join('') returns an error
anchor[i].join('') doesn't seem to have an effect.
for (var i=0; i(less than) rangeKW.length-2;i++){
anchor[i] = [];
for (var j=0; j<rangeURL.length;j++){
anchor[i][j] = ahref + rangeKW[i] + ahref1 + rangeURL[j] + "</a>|";
}
}
cell.setValue("{" + anchor);
}
Suppose you have
var x = [[1,2,3],[4,5,6]]
Then either of these lines will give you "123456":
Array.prototype.concat.apply([], x).join('')
x.map(function(a){ return a.join(''); }).join('');
The first one constructs the array [1,2,3,4,5,6] and then joins it. The second one joins each inner array first, constructing ["123", "456"] and then joins that. I think the first one is likely to be a tiny bit more efficient, although we are talking peanuts here, but the second one gives you a bit more control if you want to put something different between rows and columns.
In both cases, this doesn't change the original value in x. You can assign the new value to x if that's what you want.
array.join() works with "normal" arrays, by normal I mean 1 dimension and applies to the array itself, not on an single element (error on [i][j]), beside that I don't really understand what you want to do and how your code is related to your question ...
concerning anchor[i].join('');// doesn't seem to have an effect. I don't know how many elements are in there and how they look like but the syntax is correct. You can also use toString() if you want to make it a CSV string.
EDIT : (thanks for the information in comments.)
I think the easiest way (or at least the most clear) would be to create a couple of new variables that you could log separately to see exactly what happens.
for example
var anchorString = anchor[i].join(); // or toString() they both return strings from 1D arrays
Logger.log(anchorString)
if every index i of anchor have to be in the same cell then write it like this in the i-loop :
var anchorString += anchor[i].join();
Logger.log(anchorString)

as3 remove white space

I am trying to remove / replace white space from a string in as3. The string comes from xml and than written into text field. to compare the strings I am trying to remove white spaces
var xmlSentence:String=myXML.SENTENCE[thisSentence];
var tfSentence=e.target.text;
var rex:RegExp = /\s+/;
trace(xmlSentence.replace(rex, "-"));
trace(tfSentence.replace(rex, "-"));
That code outputs like this:
She-has a dog
-She has a dog
I also tried different rex patterns. the problem is that though there are spaces in both string -which are same- it finds only one space but not the same one in both strings.
Could you help me to solve this problem
Thanks in advance
You need to use the g flag to indicate recursive changes
var rex:RegExp = /\s+/g ;
Within your Actionscript code, select the RegExp keyword, then goto the 'Help' menu and choose 'Flash Help' for more info on flags.