James
James

Reputation:

Using JQuery within onClick

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.

Upvotes: 12

Views: 25742

Answers (4)

Michal - wereda-net
Michal - wereda-net

Reputation: 959

You can even put other jquery code like this:

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

Upvotes: 1

flatline
flatline

Reputation: 42613

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.

Upvotes: 0

brettkelly
brettkelly

Reputation: 28205

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
}

Upvotes: 5

VoteyDisciple
VoteyDisciple

Reputation: 37803

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

Upvotes: 20

Related Questions