12

Am I allowed to use JQuery within an onClick function?

For example:

<a onclick="my_save_function($("#inputID").val())">
<input type=hidden id="inputID" value="foo">

Such that, when clicked, the anchor tag runs this:

my_save_function(foo);

After a few searches, I couldn't find a similar topic. Thank you for any help.

2
  • Thank you very much for the quick responses. I never cease to be amazed by SO's community. Commented Aug 13, 2009 at 20:52
  • As seen in comments to flatline's answer, OP was getting an error message, due to not escaping the nested double-quotes. Commented Jul 15, 2020 at 21:26

4 Answers 4

20

Sure. jQuery doesn't exist in any special universe; it's just a collection of JavaScript functions that you might find (extraordinarily) useful.

However, if you're using jQuery anyway, why not properly attach the onclick event from within jQuery? You'd just have to do:

$(document).ready(function() {
    $("#id-for-that-link").click(function() {
        my_save_function($("#inputID").val());
    });
});
Sign up to request clarification or add additional context in comments.

3 Comments

It isn't always possible (or practical) if one for example is using html injection.
If you're injecting new HTML you can still attach your own handlers to it as soon as it's part of the DOM. The timing (i.e., the sequence in your code) may be a little different, but the basics of attaching an event handler aren't any different.
Attaching handlers when attaching into the DOS is not always possible. Depends on the structure of the project, if for example you only control the creation of the Html and not the code when it is injected.
5

try this (you'll need an id on the anchor tag):

<a onclick="my_save_function(this.id);">

and in your javascript:

function my_save_function(elid){
    v = $("#"+elid).val();
    // do stuff with v
}

1 Comment

This is a handy way to move the syntax complexity into a separate function.
1

You can even put other jquery code like this:

onclick="$('#myid').closest('tr').hide();"

Comments

0

Honestly, you'd already written the code and markup, couldn't you just run it and see if it worked?

In answer to your question, yes, this should work fine, but watch your nested quotations. It would be better form and easier to read/maintain if you add a click handler to the element than embed the function body in the attribute string.

3 Comments

I did try that. However, I am getting a syntax error in FireBug like this:syntax error my_save_function($( So I was not sure if JQuery is even useable within the function. That is why I asked.
Yeah I think the quotations were doing it...you either need to use single quotes on the inner set or escape out the extra double quotes.
Yea, that turned out to be exactly the problem. Thank you. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.