HelloCW HelloCW - 23 days ago 7
jQuery Question

How to submit a form by clicking a text?

I hope to submit a form when I click the

span id="ToolBarDownload"
but it seems that the
form id="myformID"
is not submitted. What's wrong? Does my code make sense? Thanks!

By the way, the text
id="ToolBarDownload"
is outside the form.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="js/jquery1.10.2.min.js?isassets=1" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#ToolBarDownload").click(function() {
if (confirm('Do you want to Download')) {
$("#myformID").commit();
}
});

$("#myformID").submit(function(eventObj) {
$('<input />').attr('type', 'hidden').attr('name', "myCw").attr('value', "mydata").appendTo('#myformID');
return true;
});
});
</script>
</head>
<body>
<div id="container">
<form action='' method='post' enctype='multipart/form-data' id="myformID"></form>
<span id="ToolBarDownload" class="ToolBarButton" style="margin-left:5px">Download</span>
</div>
</body>
</html>

Answer

There is no commit() method in jQuery. To submit a form, use submit():

$("#ToolBarDownload").click(function(){
    if (confirm('Do you want to Download')) {
        $("#myformID").submit();
    }
});

Also note that in the submit() handler you can provide an object to the attr() method to make only a single call that changes multiple attributes. return true is also redundant and can be removed:

$("#myformID").submit(function() {
    $('<input />').attr({
        type: 'hidden',
        name: 'myCw',
        value: 'mydata'
    }).appendTo('#myformID');
});