Hello
I am trying to run a function from a click event but cannot seem to get it to work. What I have done is create a normal function and then call it from a custom code that I have created using an id that I have passed. However, although when I view in console.log that the code is correct, the function is not called. Where I am stuck is how to call the function and would be grateful for any help.
I have posted the code I am using and would be grateful is someone could show me the right way to call function from my code. Many thanks
function filertv() {
if ($("#filertv").hasClass("disable")) {
$(".submitBtn").tipso({
position: 'right',
titleContent: 'File Retrieve Option Disabled',
content: 'Retrieve option will be enabled when a file is selected for retrieval',
background: '#EFF2D0',
titleBackground: '#3499BA',
color: 'black',
width: 375,
offsetX: 10
});
return false;
}
}
Ah ok… so you might define the functions on an object, and call them dynamically using the bracket accessor notation like so:
var myService = {
filertv: function () {
// Do some stuff
return 42
},
doSomethingElse: function () {
// Do some other stuff
return 'foo'
}
}
// Then somewhere else...
var method = document.querySelector('#filertv').id
if (typeof myService[method] === 'function') {
var value = myService[method]()
console.log(value)
} else {
throw new ReferenceError(method + ' is not ok')
}
The other way to go perhaps, is there a way to call from this piece of code that disables the selector based on the value of ‘id’. this works well to disable selector. Thanks
Technically, you can eval() the string to run the function. It is… very highly unrecommended to use eval if at all possible though. Something like what m3g4p0p is doing is much preferred, because it doesn’t allow execution of arbitrary code.
I’m having a little trouble in understanding the logic of your code… is there a separate function for removing the tipso?
You appear to be using jquery, so… would the bind not just be $(WhateverSelectorYourBindingTo).click(filtertv)
Hi
I am not binding to a selector. I am trying to run a function based on the attr of ‘id’. I have created a function filertv() in a sepearate js file.
The idea is when a user clicks a button ‘.selectall’ this runs the function as I posted based on the value of ‘id’. so in this case, the function is ‘filertv()’ and the id being passed is ‘filertv’. so my problem is that i cannot see a way to run say ‘fileftv();’ as a function based on my present code. Yes, tipso is destroyed elsewhere.
Then i would definitely go with m3g4p0p’s solution.
var myService = {
filertv: function () {
// Do some stuff
return 42
},
doSomethingElse: function () {
// Do some other stuff
return 'foo'
}
}
myService['filertv']();
EDIT: Except i need to spell the property name correctly.