How to pass parameter in javascript function - javascript

I want to pass one parameter to a function called ForPaste().
My function is given below:
var regex = /^[A-Za-z0-9ĀĒĪŌŪāēīōū\.\-\~\`\'' ]*$/;
var SalaryRegex = /^[A-Za-z0-9\,\.\/\$ ]*$/;
$.fn.ForPaste = function () {
return this.each(function () {
$(this).bind('input propertychange', function () {
var value = $(this).val();
if (!regex.test(value)) {
$(this).val("");
}
});
});
};
This function is in a common JS file. It is called on individual pages. I want to test the regex depending on the parameter passed. So can I know the method about to call the ForPaste() function with the parameter.e.g $("#Text1").Forpaste('FromForm1'); and I get this FromForm1 in the ForPaste() function.

You define a formal parameter for your function.
// formal parameter--v
$.fn.ForPaste = function (the_value) {
alert( the_value ); // displays the argument passed
// rest of your code
};
Whatever value was passed to ForPaste() will be referenced by the_value. (Of course you can change the name to any valid identifier.)

not sure what you are trying to do, because the answer seems so obvious. Will this do?
$.fn.ForPaste = function (theName) {
if (theName.test(//)){
return this.each(function () {
....
});
}
return false
};
you can access the parameters by looking at arguments which isn't an array, but seems to be one. from within the function you can do an var theName=arguments[0] to get the value of the first parameter

Related

Compare functions in Javascript

I have an API that takes a function as an input, and then inside the API, the intent is to add the function to an Array if the function is not already added to the Array.
The call to the API is of the form:
myApiHandle.addIfUnique(function(){
myResource.get(myObj);
});
The API is:
myApiHandle.addIfUnique(myFunc) {
if (myArray.indexOf(myFunc) === -1) {
return;
}
// add to array
}
Now this obviously does not work as expected, since each time a new function is being passed in.
My Question is: Is there a way to pass in a function into the myApiHandle.addIfUnique call that will allow me to compare the existing functions in the array with this function that is currently passed in? The comparison should compare the function name and the object, and if both are the same, then not add the function to the array. I want to avoid adding another argument to the addIfUnique call if at all possible.
In other words, is the below possible:
myApiCall.addIfUnique (someFunc) {
}
If so, what is the someFunc. And what would be the logic inside the API to detect if the function already exists in myArray?
The same problem occurs with addEventListener and removeEventListener, where the callback must be identical (in the === sense) for removeEventListener to remove it.
As you've found, obviously if you call addIfUnique like this:
addIfUnique(function() { })
the function passed each time will be a unique object. The solution is to create the function once:
var fn = function() { };
addIfUnique(fn);
addIfUnique(fn);
A related problem occurs when the function being passed in is a method invocation, so I need to bind it:
var x = { val: 42, method: function() { console.log(this.val); } };
I want to pass a bound version of it, so
addIfUnique(x.method.bind(x));
addIfUnique(x.method.bind(x));
But again, each call to x.method.bind(x) will return a separate function. So I need to pre-bind:
var boundMethod = x.method.bind(x);
addIfUnique(boundMethod);
addIfUnique(boundMethod);
First of all, comparing functions is meaningless, even if two functions are literally different, they may be functionally the same.
And for your problem, you can compare whether it's exactly the same object, or you can compare it literally by using toString() function and regExp.
var addIfUnique = (function() {
var arr = [];
return function(func) {
if (~arr.indexOf(func)) return false;
var nameArr = [];
var funcName = func.name;
var funcRegExp = new RegExp('[^\{]+\{(.+)\}$', 'i');
var funcStr = func.toString().match(funcRegExp);
funcStr = funcStr && funcStr[1];
if (!funcStr) return false;
var strArr = arr.map(function(v){
nameArr.push(v.name);
return v.toString().match(funcRegExp)[1];
});
if (~strArr.indexOf(funcStr) && ~nameArr.indexOf(funcName)) return false;
arr.push(func);
};
}());

Use value from method in javascript object to use in setTimeout function

I have tried different things but I do seem to be looking something over that is too obvious. Trying to use the value a function(method) returns inside an object and use it in another method with setTimeout within that same object.
This is the html:
<h1>3000</h1>
The javascript (jQuery in this case):
var foo = {
getValue: function() {
var h1Text = $('h1').text();
h1Text = parseInt(h1Text);
return h1Text;
},
useValue: function() {
var time = this.getValue();
var alertIt = alert('Hello');
setTimeout(alertIt,time);
}
};
foo.useValue();
// log shows correct value
console.log(foo.getValue());
// returns a number
console.log(typeof(foo.getValue()));
The alert does show up, but on load rather than using those 3 seconds.
It does log the correct value and also says it's a number so I'm really not sure what I am doing wrong. Any help is appreciated. Thanks
In useValue() you call alert('Hello'), so it's executed immediately and the result is stored in alertIt variable. You should put it inside the function like this, as setTimeout expects a function as a first parameter:
var alertIt = function() {
alert('Hello');
}
setTimeout(alertIt,time);
setTiimeout expects function and not variable.
Also var alertIt = alert('Hello'); this will return undefined.
Note: var a = function() will call it and assign return value. To assign a function to a variable with parameter, use .bind
Try alert.bind(null, "hello");
For demo purpose, I have hardcoded value of delay and commented getValue code.
var foo = {
getValue: function() {
//var h1Text = $('h1').text();
//h1Text = parseInt(h1Text);
return true// h1Text;
},
useValue: function() {
var time = 3000//this.getValue();
var alertIt = alert.bind(null,'Hello');
setTimeout(alertIt, time);
}
};
foo.useValue();
// log shows correct value
console.log(foo.getValue());
// returns a number
console.log(typeof(foo.getValue()));

Javascript: Combine function argument with string to reference var

I have vars that look like this:
var cardholder = $("#cardholder");
var cardholderInfo = $("#cardholder-Info");
And a function (which doesn't currently work) that looks like this:
function validateRequired(field){
//if it's NOT valid
if(field.val().length < 1){
field.addClass("field_error");
fieldInfo.text("(Required)");
fieldInfo.addClass("error");
return false;
}
//if it's valid
else{
field.removeClass("field_error");
fieldInfo.text("");
fieldInfo.removeClass("error");
return true;
}
}
Which I access like:
cardholder.keyup(validateRequired(cardholder));
I've looked everywhere but I can't find what I need and I'm not really sure what I should be searching for.
I can use the field value to access the straight cardholder var. But I also want to use the field value to then reference cardholderInfo so I can manipulate that element in the function.
You would call the function like this, passing the second parameter:
cardholder.keyup(function () {
validateRequired(this, cardholderInfo);
});
And modify your function to take a second parameter:
function validateRequired(field, fieldInfo){
/* validation stuff */
}
No need for the global variables:
function validateRequired($cardInfo){
// You can guess what $cardInfo is
//if it's NOT valid
if(this.val().length < 1){
this.addClass("field_error");
$cardInfo.text("(Required)");
$cardInfo.addClass("error");
return false;
}
//if it's valid
else{
this.removeClass("field_error");
$cardInfo.text("");
$cardInfo.removeClass("error");
return true;
}
}
$(document).ready(function(){
$("#cardholder").keyup(function(){
validateRequired.call($(this),$("#cardholder-Info"));
});
});
Don't call the function you want to bind! If you need to pass an argument to it every time it is called, you either need to use bind or a function expression:
cardholder.keyup(functio(e) {
return validateRequired(cardholder, cardholderInfo);
});
Also you will need a second parameter in your validateRequired function to get the fieldInfo variable filled:
function validateRequired(field, fieldInfo){
…
You have to pass reference of function in keyup, you do not have to call function
cardholder.keyup(function(){
validateRequired(cardholder)
});

Make initial capital in a user-supplied control name

I have a function with the name MakeInitialCapital. I want to supply control name as an argument and the text in that control must be converted to Initial Capital.
How to modify this Javascript code:
function MakeInitialCapitalControl(controlName)
{
TextInControl = getElementByID(controlName).value;
return str.toLowerCase().replace(/\b[a-z]/g, cnvrt);
function cnvrt() {
return arguments[0].toUpperCase();
}
Edited:
One more thing, if the text already has Intials Capital, make it lowercase.
Assuming the rest of your code works, you need to assign the value, rather than returning it:
function MakeInitialCapitalControl(controlName)
{
var ctrl = getElementByID(controlName);
ctrl.value = ctrl.value.toLowerCase().replace(/\b[a-z]/g, function {
return arguments[0].toUpperCase();
});
}
EDIT
As for the request in your edit... that's a rather strange request. Are you sure you want that in the same function? It'll do pretty much the exact opposite of what the function name implies. But oh well:
function MakeInitialCapitalControl(controlName)
{
var ctrl = getElementByID(controlName);
if(/^[A-Z]/.test(ctrl.value)) {
ctrl.value = ctrl.value.toLowerCase();
return;
}
ctrl.value = ctrl.value.toLowerCase().replace(/\b[a-z]/g, function {
return arguments[0].toUpperCase();
});
}

Can i use a function name in my jquery plugin parameters?

I am creating a form validation plugin for jQuery and would like it to call a function once the form has been successfully validated.
The plugin will have a default callback function, but I would like to modify this through the options parameter.
Unfortunately what i have (below) does not work. Any ideas?
(function($){
$.fn.extend({
validify : function(options) {
var defaults = {
callback: "callbackFunc",
};
var options = $.extend(defaults,options);
return this.each(function(){
//validation code here
//if valid call the function
if(errors==0){
options.callback;
}
function callBackFunc(){
// the default callback function
}
...
Remove the quotes and you're golden.
This will pass a function reference. You can then call it by doing options.callback();
You will also need to declare the function before you pass the reference along. You could get around this by doing this instead:
callback: function() { callbackFunc(); }
Pass the function itself, rather than its name (ie, remove the quotes):
(function($){
function callBackFunc(){
// the default callback function
}
$.fn.extend({
validify : function(options) {
var defaults = {
callback: callbackFunc // IMPORTANT: remove quotes AND trailing comma
};
var options = $.extend(defaults,options);
return this.each(function(){
//validation code here
//if valid call the function
if(errors==0){
options.callback(); // note parentheses
}
...

Categories

Resources