$(function(){
function f1(){}
function f2(){}
}
<Input type = radio Name = radiobutton Value = "something" checked=checked onClick= //here call f1()//>
I try to get access to f1 function in OnClick
code like this doesn't work:
$.function.f1()
$.function().f1()
2 Answers 2
That's because you should be doing it something like this:
$(function () {
function foo () { }
function bar () { }
// bind
$('input').on('click', foo);
});
... instead of putting an onclick= attribute on your HTML markup.
EDIT
As requested, some quick notes on why you should do the jQuery bind instead of the onclick markup thing.
- You're already using jQuery, plain and simple. Use it.
- There should be significant effort made to separate your HTML, CSS and JS. HTML in HTML files, JS in JS files, blah. Putting in
onclick=do_backflips()in your HTML markup violates that, and will lead to nightmarish maintenance issues in the future, among other things. - DOM0
onclick=syntax is inherently1:1. Which means that naturally, for each event of each element, you only get to attach one single event handler. That definitely sucks balls. - By defining your
f1andf2functions inside thedocument.readyhandler function, you're limiting their scope within that function. This means that they can't be referenced outside that scope, which means that the script interpreter won't know aboutf1where your HTML markup is. You have to attach event handlers where the handlers are known, and that's insidedocument.ready(if that makes sense).
3 Comments
The point of using $( function(){ ... } ) is that whatever inside is run only after the DOM has finished loading. There's no benefit to defining functions there unless the goal is to keep the namespace clean and use the functions in the local scope.
In this case you need the functions outside the scope so just move them outside the anonymous function or bind the event to the radio button inside the scope.
$(function () { ... });. funcitons f1 and f2 are out of scope and so you won't be able to access it from inline DOM. As far as I know ($.function.f1() / $.function().f1()) are syntactically invalid.onClickattributes in your HTML. Use.on('click', ...)instead; it keeps your JavaScript and HTML strictly separated.