i want javascript code to check whether my input text is in specific format as AS0301-12345
<apex:inputText id="searchText" value="{!searchText}" onmousemove="checkingstring(this)"/>
<script>
function checkingstring(searchText){
var pattern = "([a-zA-Z](2)[0-9](4)-[0-9](5))"; /// is it correct
var regexp = new System.Text.RegularExpressions.Regex(pattern);
var userInput = "(123) 555-1243";
if (!regexp.IsMatch($component.searchText))
{
alert("The syntax is always as follows: AANNNN-NNNNN (A= Alpha/Letter; N= Number) i.e.FL0301-12345</b>");
}
}
</script>
Your JS function should look more like this:
function checkingstring(inputElem) {
var regex = /^[A-Z]{2}[0-9]{4}-[0-9]{5}$/i;
var searchText = inputElem.value;
if (searchText.length && !regex.test(searchText)) {
alert('The syntax is always as follows: AANNNN-NNNNN \n' +
'(A: Alpha/Letter; N: Number), e.g. FL0301-12345');
}
}
You should probably also change the onmousemove to something more meaningful, like onblur maybe.
Take a look at this short demo.
This is how I'd do it. There is a lot of functionality you can squeeze into shorthand. Changed onMouseMove to onChange so instead of checking whenever the mouse moves it should check when an edit of searchText completes.
<apex:inputText id="searchText" value="{!searchText}" onChange="checkingstring(this)"/>
<script>
function checkingstring(searchText){
var regexp = /^[A-Z]{2}\d{4}-\d{5}$/i; //AANNNN-NNNNN A = Capital N = Number
if (!regexp.exec(searchText.value)) {
alert("The syntax is always as follows: AANNNN-NNNNN (A= Alpha/Letter; N= Number) i.e.FL0301-12345</b>");
}
}
</script>
got some ideas from w3schools js regexp page.
Related
World!
I'm trying to create a program in Javascript that takes the log of a number typed into an HTML input. Unfortunately i've encountered a problem where it wont accept the string with the .replace().
Its Function:
I.E: When log(10) is calculated, the function should first remove the first 4 char's "log(" next remove the last parenthesis ")" and then take the log of the no. between.
HTML includes style elements, button and input form and an output < DIV >.
//Function
function calculate()
{
var inputString = document.getElementById("inpstr");
var output = document.getElementById("output");
//TESTING CODE
/*
if (inputString.value.startsWith("log(").endsWith(")"))
{
console.log(output.innerHTML = inputString.value.substring(4, 20).replace(")", ""));
}
else
{
output.innerHTML = "false";
}
*/
//Math.log() calc *****DOESNT WORK*****
if (inputString.value.startsWith("log(").endsWith(")"))
{
output.innerHTML = Math.log(inputString.value.replace(")", "").substring(4, 20));
}
else
{
output.innerHTML = inputString.value;
}
event.preventDefault();
}
If someone can give me an effective solution that would be much appreciated.
Thanks,
Syntax
Since Math.log() accepts only number values and you're trying to pass a string to it, you should first parse this value into a float number and then pass it to the log function:
let val = parseFloat(inputString.value.replace(")", "").substring(4, 20));
output.innerHTML = Math.log(val);
I'm guessing I got downvoted for being lazy, so here is the quick info. Gonras got it right relating to what you want to extract, but he forgot to check that what's being input is actually a log.
That's where the regex below comes in handy! I'm matching the field to:
^ start of word, since we want to match the entire field.
log(
([-.\d])) any consecutive sequence () of numbers (\d), -, and '.', represented by the []. The \(...\) makes sure to save this inner part for later.
$ is end of word, see 1.
res will be null if there is no match. Otherwise, res[0] is the entire match (so the entire input field) and res[1] is the first 'capture group', at point 3 - which is presumably the number.
This of course fails for multiple "-" inside, or "." etc... so think it over.
//Function
function calculate()
{
var inputString = document.getElementById("inpstr");
var output = document.getElementById("output");
var res = /^log\(([-.\d]*)\)$/.exec(inputString.value);
if (res)
output.innerHTML = Math.log(res[1]);
else
output.innerHTML = res;
}
document.getElementById("output").innerHTML='start';
calculate()
<div id='output'></div>
<input id='inpstr' value='log(2.71828)'></input>
If I wanted to fix your if to supplement Gonras's solution:
if (inputString.value.startsWith("log(") && inputString.value.endsWith(")"))
Yours fails since startsWith() returns a boolean, which obviously doesn't have a endsWith function.
Where am I going wrong? Even one error would help please.
I have an HTML input and a submit button. The idea is to:
Submit search string
Get string value.
Compare string value to regex.
If legit, find instances of the string in the DOM.
Then scroll to the first instance of the matched string as it sits in the DOM.
$("#submit").on("click", function () {
//regex to be compared against
var search = new RegExp();
search = /(^\w[A-z]+)$|(^\d[0-9\.x\.X\.m\.M]+)/;
//grab the string value from the search input
var userin = $("#searchin").val();
var compare = userin.test(search);
if (compare === true) {
var treebody = $('html, body').contents().filter(function (userin) {
if ($('html, body').contents() === userin) {
$('html, body').animate({'scrollTop' : $(treebody).position().top}, 700)
} else {
alert("Please search again or scroll down to find your desired content");
}
});
} else {
alert("Sorry, we couldn't match your search. Please try a region or place or a billboard size e.g. 9x13 ");
}
});
Change the line
var compare = userin.test(search);
it should be
var compare = search.test(userin);
Also check you regular expression. Here is a good reference RegEx.
Aanval op Vlemis (499|453) C44
This is what the string looks like. Though it's actually like this: "Aanval op variable (variable) variable
What I want to do is 1: get the coordinates (I already have this), 2 get Vlemis (first variable), get C44 (third variable) and check to see if the string is of this type.
My code:
$("#commands_table tr.nowrap").each(function(){
var text = $(this).find("input[id*='editInput']").val();
var attackername= text.match(/(?=op)[\s|\w]*(?=\()/);
var coordinates = text.match(/\(\d{1,3}\|\d{1,3}\)/);
});
Coordinates works, attackername however doesn't.
Html:
<span id="labelText[6]">Aanval op Vlemis (499|453) C44</span>
You should use one regex to take everything :
var parts = text.match(/(\w+)\s*\((\d+)\|(\d+)\)\s*(\w+)/).slice(1);
This builds
["Vlemis", "499", "453", "C44"]
If you're not sure the string is valid, test like this :
var parts = text.match(/(\w+)\s*\((\d+)\|(\d+)\)\s*(\w+)/);
if (parts) {
parts = parts.slice(1);
// do things with parts
} else {
// no match, yell at the user
}
I've done some digging on the above topic but am now more confused than when I started.
I have a unit converter that I'm working on.
It's working fine as a base model but I'm now trying to make it more modular.
There are many units and many conversions.
My plan is to have a function that determines what type of conversion is required, temperature, area etc etc, that can then call the appropriate function to carry out the math.
I'm very new to JS which isn't helping matters as it could be a simple mistake that I'm making but it's just as likely that I'm getting huge errors.
I think the problem is passing the object to the next function and then using it.
I've played with the code a great deal and tried many different suggestions online but still no success.
here is my code:
<script type="text/javascript">
function Convert(from, to, units, res){
this.from = from;
this.to = to;
this.units = units;
this.res = res;
}
Convert.convertUnits = function(){
var measurementType = $(".from option:selected").attr("class");
var result = "invalid input";
var input = parseInt(this.units.val());
if(measurementType == "temp"){
var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
test.convertTemp();
console.log('Did we get this far?!?! ::', measurementType);
}
console.log('or not???? ::', measurementType);
}
Convert.prototype.convertTemp = function(){
var result = "invalid input";
var input = parseInt(this.units.val());
var f = this.from.val();
var t = this.to.val()
if(!isNaN(input)) {
if(f == "degC"){
if(t == "degF"){
result = input * 1.8 + 32;
}
if(t == "kelvin"){
result = input + 273.15;
}
}
}
console.log('Parsed input is', input, "and result is", result);
this.res.val(result);
return result;
}
//var calcTempTest = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
//var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
$("#btnConvert").click.convertUnits();
</script>
The first obvious problem is this line:
$("#btnConvert").click.convertUnits();
This tries to call a convertUnits() method defined on the click method of the jQuery object returned by $("#btnConvert"). There is no such method, so you get'll get an error about how click has no method 'convertUnits'.
What you want to be doing there is binding the convertUnits() function as a click handler, which you do by passing it to the .click() method as an argument:
$("#btnConvert").click(Convert.convertUnits)
It doesn't make sense to have declared convertUnits() as a property of Convert(), though, so (although it will work as is) I'd change it to just be:
function convertUnits() {
// your code here
}
$("#btnConvert").click(convertUnits);
The only other thing stopping the code working is that on this line:
var input = parseInt(this.units.val());
...you use this assuming it will be a Convert object with a units property but you haven't yet created a Convert object - you do that inside the if(measurementType == "temp") block with this line:
var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
So move that line to the beginning of the function and then use test instead of this:
function convertUnits(){
var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
var measurementType = $(".from option:selected").attr("class");
var result = "invalid input";
var input = parseInt(test.units.val());
if(measurementType == "temp"){
test.convertTemp();
console.log('Did we get this far?!?! ::', measurementType);
}
console.log('or not???? ::', measurementType);
}
Working demo: http://jsfiddle.net/jT2ke/
Some unrelated advice: parseInt() doesn't really make sense for a number to feed into your converter, because the user might want to enter decimal values. You can use parseFloat() instead, or the unary plus operator:
var input = +test.units.val();
But if you want parseInt() it is generally recommended to pass it a second argument to specify the radix:
var input = parseInt(test.units.val(), 10);
...because otherwise if the input text has a leading zero some browsers will assume the value is octal rather than base ten. (parseFloat() and the unary plus don't have that issue.)
I think you should not implement the method convertUnits inside Convert object. And the new code will look like the following:
convertUnits = function(){
var measurementType = $(".from option:selected").attr("class");
var result = "invalid input";
if(measurementType == "temp"){
var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
test.convertTemp();
console.log('Did we get this far?!?! ::', measurementType);
}
console.log('or not???? ::', measurementType);
}
Now you can initiate the convertUnits on the button click:
$("#btnConvert").click(function(){new convertUnits()});
I'm struggling with a ExtJS 4.1.1 grid that has editable cells (CellEditing plugin).
A person should be able to type a mathematic formula into the cell and it should generate the result into the field's value. For example: If a user types (320*10)/4 the return should be 800. Or similar if the user types (320m*10cm)/4 the function should strip the non-mathematical characters from the formula and then calculate it.
I was looking to replace (or match) with a RegExp, but I cannot seem to get it to work. It keeps returning NaN and when I do console.log(e.value); it returns only the originalValue and not the value that I need.
I don't have much code to attach:
onGridValidateEdit : function(editor,e,opts) {
var str = e.value.toString();
console.log(str);
var strCalc = str.match(/0-9+-*\/()/g);
console.log(strCalc);
var numCalc = Number(eval(strCalc));
console.log(numCalc);
return numCalc;
},
Which returns: str=321 strCalc=null numCalc=0 when I type 321*2.
Any help appreciated,
GR.
Update:
Based on input by Paul Schroeder, I created this:
onGridValidateEdit : function(editor,e,opts) {
var str = e.record.get(e.field).toString();
var strCalc = str.replace(/[^0-9+*-/()]/g, "");
var numCalc = Number(eval(strCalc));
console.log(typeof numCalc);
console.log(numCalc);
return numCalc;
},
Which calculates the number, but I am unable to print it back to the grid itself. It shows up as "NaN" even though in console it shows typeof=number and value=800.
Final code:
Here's the final code that worked:
onGridValidateEdit : function(editor,e,opts) {
var fldName = e.field;
var str = e.record.get(fldName).toString();
var strCalc = str.replace(/[^0-9+*-/()]/g, "");
var numCalc = Number(eval(strCalc));
e.record.set(fldName,numCalc);
},
Lets break this code down.
onGridValidateEdit : function(editor,e,opts) {
var str = e.value.toString();
What listener is this code being used in? This is very important for us to know, here's how I set up my listeners in the plugin:
listeners: {
edit: function(editor, e){
var record = e.record;
var str = record.get("your data_index of the value");
}
}
Setting it up this way works for me, So lets move on to:
var strCalc = str.match(/0-9+-*\/()/g);
console.log(strCalc);
at which point strCalc=null, this is also correct. str.match returns null because your regex does not match anything in the string. What I think you want to do instead is this:
var strCalc = str.replace(/[^0-9+*-]/g, "");
console.log(strCalc);
This changes it to replace all characters in the string that aren't your equation operators and numbers. After that I think it should work for whole numbers. I think that you may actually want decimal numbers too, but I can't think of the regex for that off the top of my head (the . needs to be escaped somehow), but it should be simple enough to find in a google search.