tags:

views:

382

answers:

3

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.

+7  A: 

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());
    });
});
VoteyDisciple
A: 

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
}
inkedmn
A: 

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.

flatline
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.
flatline
Yea, that turned out to be exactly the problem. Thank you. :)