Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
143
rated 0 times [  149] [ 6]  / answers: 1 / hits: 140706  / 13 Years ago, fri, may 20, 2011, 12:00:00

I have a form where i've replaced the submit button with an input (with type=button) with an onclick which calls an existing function:



<form accept-charset=UTF-8 action=/admin/message_campaigns class=new_message_campaign id=new_message_campaign method=post>
<!-- some fields -->
<input onclick=confirmSubmit(); type=button value=Send />
</form>


In the confirmSubmit, i'd like to be able to dynamically get the form object (to submit it), instead of having to hardcode the form's id, or pass it as part of the call to confirmSubmit(). I'd have thought that i could do this by first getting the dom element that was clicked on, ie something like this:



var form = $(this).parents(form);


where $(this) is the object that called the function, ie the input with the onclick. This doesn't work though. I think it would work if i'd set it up with the .click(function(){ syntax. Can i get the element that called the function in a different way?



EDIT - got the answer from @claudio below, for clarity here's the complete function and call:



<form accept-charset=UTF-8 action=/admin/message_campaigns class=new_message_campaign id=new_message_campaign method=post>
<!-- some fields -->
<input onclick=confirmSubmit($(this)); type=button value=Send />
</form>


and the function itself. Note that 'jConfirm' is a method of the jquery-alerts plugin (http://abeautifulsite.net/blog/2008/12/jquery-alert-dialogs/) but that's not really relevant to this question - the key thing was just to get the form object, not what's subsequently done with it:



function confirmSubmit(caller) {
var form = caller.parents(form);
jConfirm('Are you sure?', 'Please Confirm', function(result){
if (result) {
form.submit();
} else {
return false;
}
});
}

More From » jquery

 Answers
23

You can pass the inline handler the this keyword, obtaining the element which fired the event.



like,



onclick=confirmSubmit(this);

[#92140] Wednesday, May 18, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
janettejordynm

Total Points: 550
Total Questions: 94
Total Answers: 98

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
janettejordynm questions
Tue, Nov 24, 20, 00:00, 4 Years ago
Sat, May 23, 20, 00:00, 4 Years ago
Mon, Apr 6, 20, 00:00, 4 Years ago
Tue, Feb 18, 20, 00:00, 4 Years ago
;