This a function that allows people to type only English characters and numbers in a text field. Basically I need to update this function and allow to type in symbols too. I don't know anything about javascript function and I would appreciate if someone could send me the updated function. I know it might be really easy to do it if I knew how to code 🙃
Is there anyone who can help? Thank you
function add_js_code() {
echo "<script>jQuery('.wc-pao-addon-wrap input[type=\"text\"], .wc-pao-addon-wrap textarea').keyup(function(){
var input_val = jQuery(this).val();
var inputRGEX = /^[a-zA-Z0-9]*$/;
var inputResult = inputRGEX.test(input_val);
if(!(inputResult))
{
this.value = this.value.replace(/[^a-z0-9\s]/gi, '');
}
});</script>";
}
add_action( 'wp_footer', 'add_js_code' );
Replace your regex
FROM
var inputRGEX = /^[a-zA-Z0-9]*$/;
TO
var inputRGEX = /^[a-zA-Z0-9!##\$%\^\&*\)\(+=._-]/;
You can also modify the
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.
I want to use $htppBackend to mock some service. My problem is some of service url have parameter, ex: http://domain/service1?param1=a¶m2=b
I need an regex which can reconize http://domain/service1<whatever> is correct for http://domain/service1?param1=a¶m2=b. One thing, the first part http://domain/service1 is not a constant, it can be http://domain/service2/sth/anything.
Please help. Thanks.
Edit:
I put my code here to make it easy to understand.
I have 4 api urls:
angular
.module('moduleName')
.constant('getApi', {
attrList: 'http://domain/setup/attrList',
eventList: 'http://domain/setup/eventList',
vcList: 'http://domain/api/list1',
getRaDetails: 'http://domain/abc/getDetails?raId={0}&bookId={1}'
});
With attrList, eventList and vcList, they are ok with
$httpBackend.whenGET(getApi.attrList).respond(responseObject);
$httpBackend.whenGET(getApi.eventList).respond(responseObject);
$httpBackend.whenGET(getApi.vcList).respond(responseObject);.
But the last one getRaDetails, it doesn't work with
$httpBackend.whenGET(getApi.getRaDetails).respond(responseObject); because raId and bookId have different value each times.
Now I need a regex to make this rule - $httpBackend.whenGET(getApi.getRaDetails).respond(responseObject); works with all raId and bookId value.
Hope it can explain my question more clearly. Thanks
I need an regex which can reconize http://domain/service1 is
correct for http://domain/service1?param1=a¶m2=b
I don't think a regex is required here. Just simply check
var stringPattern = "http://domain/service1";
var input = "http://domain/service1?param1=a¶m2=b";
if ( input.indexOf( stringPattern ) == 0 )
{
alert( "correct" );
}
else
{
alert( "Incorrect" );
}
So, if you are parsing Urls, it's best to use the URL object in JavaScript:
var input = 'http://domain/abc/getDetails?raId={0}&bookId={1}';
var test = 'http://domain/abc/getDetails';
var testUrl = new URL(test);
var inputUrl = new URL(input);
then test the various bits:
if(testUrl.pathname === inputUrl.pathname){
// they both have /abc/getDetails as the path
}
This's my working code:
_(getApis).each(function (api) {
var val = api.value.split('?')[0].replace(/\//g, '\\/'),
reg = new RegExp(val);
$httpBackend.whenGET(reg).respond(dummy[api.key]);
});
Thanks all.
I am making a function to validate form input data (for practice) and maybe i'll also use it.
I was wondering if there is some way to apply the same functionality without eval as i have heard that it is bad on the js interpreter. Also improvements, if any. And also i would like to know if there is something that does the same job, ie, to apply reusable regex rules to input fields.
Here is my JavaScript validation function.
function validate(){
var num=/[0-9]+/g;
var alphanum=/[0-9a-zA-Z_]+/g;
var alphanumSpace=/[0-9a-zA-Z\w_]+/g;
var alpha=/[a-zA-Z]+/g;
var alphaSpace=/[a-zA-Z\w]+/g;
var alphanumDot=/[0-9a-zA-Z\._]+/g;
var money=/[0-9]+\.?[0-9]{0,2}?/g;
var flag=true;
var alertBox="Incorrect entries:\n\n";
$.each($('input[data-check]'),function(index,value){
if(!eval(value.dataset.check+'.test("'+value.value+'")')){
alertBox+=value.name+",\n";
flag=false;
}
});
alert(alertBox);
return flag;
}
Which is used to call on a form as
<form onsubmit="return validate()">
On fields that have the data-check attribute as any of the matching variables that i have defined as
<input data-check='num'>
This will call the test the regex against the num regex as defined in my code.
You can do something like this using new RegExp and window[]:
$.each($('input[data-check]'),function(index,value){
var str = value.value;
var patt = new RegExp(window[value.dataset.check]);
var res = patt.test(str);
if(!res){
alertBox+=value.name+",\n";
flag=false;
}
});
I'm having a problem with splitting strings in Javascript in Max/MSP.
outlet is the Max/MSP version of printf etc.
The string splits weirdly, but it seems to only output both words comma seperated.
function sample_callback(args) // Callback
{
var keyword=args;
var trackname=keyword.toString().split(" ");
var name = trackname[0]; // trackname[1] outputs nothing.
outlet(0, name);
}
Any help is greatly received.
Big thanks to Aaron Kurtzhals . Hopefully the upvote in the comment counts towards your rep!
A simple overlooked checking of what the string is helped me out. oops. The working code is now..
function sample_callback(args) // Callback
{
var keyword=args.toString();
var trackname=keyword.split(",");
var name = trackname[0];
outlet(0, name);
}
Cheers
function sample_callback(args) // Callback
{
var keyword=args.toString()`enter code here`;
var trackname=keyword.toString().split(" ");
var name = trackname[0]; // trackname[1] outputs nothing.
outlet(0, name);
}
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.