This is a JavaScript question.
Given the following code:
<input type="button" name="applyFilter" value="Apply Filter" onClick="doSubmit('applyFilter')"/>
function doSubmit(action) {
f=document.forms[0];
f.action=action;
f.submit();
}
How can I obtain the form object of the button clicked within doSubmit()? Currently, you see a reference to forms[0] but I want this to work with multiple forms on the page and I do not want to pass in the form name/id/reference or the button object reference. The button is on a form and I hope doSubmit(action) function can get that form object.
3 Answers 3
If you attach the listener dynamically you can use the related event object. There is no way to do it otherwise in a cross-browser way (IE has window.event but that isn't W3C compatible or supported by a good percentage of commonly used browsers).
Comments
Maybe you can try 'bubble' of event. I mean you can use event.target or event.srcElement.
1 Comment
using jQuery
$('input[type="button"]').on('click',function(){
$(this).parents('form').submit();
})
2 Comments
doSubmit() function.this.form.submit(), which is more efficient and less to type. And not what the OP wants. If it was, it could be done directly from the inline listener.
doSubmit()somehow unique to different forms? If not, given you've said you won't do something likeonclick="doSubmit('applyFilter',this);I don't see how you can get the form - as it stands thedoSubmit()function doesn't even have a reference to the button so how can it work out which form is related to a button it doesn't know about? (In IE you could perhaps usewindow.eventto get the details, but not in other browsers.)doSubmit()function entirely by changing the button totype="submit"and then usingonclick="this.form.action='applyFilter';".)doSubmit(this, 'action')all over my jsps only to find out at the end that passing button object reference isn't required. This is why I decided to ask here...