Calling a jQuery function with parameters
I have a btn
<a href="#" id="submitBtn" cl开发者_运维问答ass="btnGray">Upload Docs</a>
and a jquery code to submit the form.
$("#docSaveBtn").click(function(){
$("#docForm").submit();
});
I have multiple forms on the same page and I want to send the form id to submit which will submit the desired form when click of button with class 'btnGray'.
Your help is highly appreciated.
Custom data attributes
One ideal solution would be to use custom data attributes on the anchor itself, informing jQuery which form should be submitted when the anchor is clicked.
<a data-form="bears">Submit Bears</a>
<form id="bears"></form>
In the above example, we're stating that we would like our anchor to have an association with our form that immediately follows. Now we provide the logic via jQuery:
$("a[data-form]").on("click", function(e){
var formName = $(this).data("form");
$("#" + formName).submit();
});
Example: http://jsfiddle.net/65HPj/
Proximity-based Submission...
A much cleaner solution would be proximity-based, where a link submits it's closest form:
$(".submitBtn").click(function(e){
e.preventDefault();
$(this).closest(".linkFormBlock").find("form").submit();
});
<div class="linkFormBlock">
<a href="submitBtn">Upload Docs</a>
<form>
<input type="text" name="specialValues" />
</form>
</div>
$(".btnGray").click(function(){ $("#docForm").submit();});
If you want to use the submit()
method, you could just include any relevant parameters in your action
attribute of your form
tag. e.g:
<form action="/formProcessor.aspx?id=1234">
....
<a href="#" id="submitBtn" class="btnGray">Upload Docs</a>
....
</form>
Using the jQuery you supplied in your question, this will automatically submit your form using the action designated in your form
tag.
精彩评论