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; } }); }
The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.
trigger( "click" ); As of jQuery 1.3, . trigger() ed events bubble up the DOM tree; an event handler can stop the bubbling by returning false from the handler or calling the . stopPropagation() method on the event object passed into the event.
$('button'). click(function(event, wasTriggered) { if (wasTriggered) { alert('triggered in code'); } else { alert('triggered by mouse'); } }); $('button').
To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked.
You can pass the inline handler the this
keyword, obtaining the element which fired the event.
like,
onclick="confirmSubmit(this);"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With