【发布时间】:2022-01-13 09:28:27
【问题描述】:
我有一个 html 代码,其中包含多个 ID 为 form01、form02 等的表单。
我正在使用 jQuery 提交表单。对于每个表单,我使用 javascript 和 jQuery 为不同的表单 ID(form01、form02 等)编写了相同的代码。如果我这样做,事情就会奏效,但这不是一种好的编程方式。因此,我创建了一个以表单 ID 作为输入参数的 javascript 函数,并使用提交按钮的 onclick 事件调用此函数。
在函数内部,我使用这个参数(来自 ID)来提交表单,但这不起作用。有人可以帮我解决这个问题吗?
提前致谢。
我的代码如下:
<html>
<head>
<title>Main Page</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.0/themes/base/jquery-ui.css">
<link rel="stylesheet" href="include/jquery-ui-1.13.0.custom/jquery-ui.css">
<script type="text/javascript" src="include/jscript/jquery-3.6.0.min.js "></script>
<script type="text/javascript" src="include/jquery-ui-1.13.0.custom/jquery-ui.js"></script>
<script>
$(document).ready(function(){
$("#form01").on("submit", function(event){
event.preventDefault();
var formValues= $(this).serialize();
$.post("./form01OutPut.php", formValues, function(data){
// Display the returned data in browser
$("#divOutPut").html(data);
});
});
});
$(document).ready(function(){
$("#form02").on("submit", function(event){
event.preventDefault();
var formValues= $(this).serialize();
$.post("./form01OutPut.php", formValues, function(data){
// Display the returned data in browser
$("#divOutPut").html(data);
});
});
});
function submitFrm(x)
{
alert(x);
$(document).ready(function(){
$(x).on("submit", function(event){
event.preventDefault();
var formValues= $(this).serialize();
$.post("./form01OutPut.php", formValues, function(data){
// Display the returned data in browser
$("#divOutPut").html(data);
});
});
});
}
</script>
</head>
<body>
<table>
<form id="form01" name="form01" action="./form01OutPut.php" method="post">
<tr>
<td>
Enter text:
</td>
<td>
<input type="text" id="txt01" name="txt01" size=10>
</td>
<td>
<input type="button" id="submitBtn01" name="submitBtn01" value="Submit" onclick="submitFrm('#form01')">
<!-- <input type="submit" id="submitBtn01" name="submitBtn01" value="Submit"> -->
<!-- <input type="submit" value="Submit"> -->
</td>
</tr>
</form>
<form id="form02" name="form02" action="./form01OutPut.php" method="post">
<tr>
<td>
Enter text:
</td>
<td>
<input type="text" id="txt02" name="txt02" size=10>
</td>
<td>
<!-- <input type="button" id="submitBtn" name="submitBtn" value="Submit"> -->
<input type="submit" id="submitBtn02" name="submitBtn02" value="Submit">
<!-- <input type="submit" value="Submit"> -->
</td>
</tr>
</form>
</table>
<div id="divOutPut">
</div>
</body>
【问题讨论】: