jQuery:清除表单输入
我尝试过不同的方法来清除表单:
<form action="service.php" id="addRunner" name="addRunner" method="post">
First Name: <input type="text" name="txtFirstName" id="txtFirstName" /><br />
Last Name: <input type="text" name="txtLastName" id="txtLastName" /><br />
Gender: <select id="ddlGender" name="ddlGender"><option value="">--Please Select--</option>
<option value="f">Female</option>
<option value="m">Male</option>
</select><br />
Finish Time:
<input type="text" name="txtMinutes" id="txtMinutes" size="10" maxlength="2">(Minutes)
<input type="text" name="txtSeconds" id="txtSeconds" size="10" maxlength="2">(Seconds)
<br />
<button type="submit" name="btnSave" id="btnSave">Add Runner</button>
<input type="hidden" name="action" value="addRunner" id="action">
</form>
jQuery #1:
function clearInputs(){
$("#txtFirstName").val('');
$("#txtLastName").val('');
$("#ddlGender").val('');
$("#txtMinutes").val('');
$("#txtSeconds").val('');
}
这非常有效。
jQuery #2:
function clearInputs(data){
$("#addRunner :input").each(function(){
$(this).val('');
});
这会清除表单,但不允许我向其提交更多信息。我尝试再次单击该按钮,但什么也没做。
这是按钮单击处理程序:
$("#btnSave").click(function(){
var data = $("#addRunner :input").serializeArray();
$.post($("#addRunner").attr('action'), data, function(json){
if (json.status == "fail"){
alert(json.message);
}
if (json.status == "success"){
alert(json.message);
clearInputs();
}
}, "json");
});
PHP 邮政代码:
<?php
if($_POST){
if ($_POST['action'] == 'addRunner') {
$fname = htmlspecialchars($_POST['txtFirstName']);
$lname = htmlspecialchars($_POST['txtLastName']);
$gender = htmlspecialchars($_POST['ddlGender']);
$minutes = htmlspecialchars($_POST['txtMinutes']);
$seconds = htmlspecialchars($_POST['txtSeconds']);
if(preg_match('/[^\w\s]/i', $fname) || preg_match('/[^\w\s]/i', $lname)) {
fail('Invalid name provided.');
}
if( empty($fname) || empty($lname) ) {
fail('Please enter a first and last name.');
}
if( empty($gender) ) {
fail('Please select a gender.');
}
if( empty($minutes) || empty($seconds) ) {
fail('Please enter minutes and seconds.');
}
$time = $minutes.":".$seconds;
$query = "INSERT INTO runners SET first_name='$fname', last_name='$lname', gender='$gender', finish_time='$time'";
$result = db_connection($query);
if ($result) {
$msg = "Runner: ".$fname." ".$lname." added successfully" ;
success($msg);
} else {
fail('Insert failed.');
}
exit;
}
}
如果我使用 jQuery 方法 #2,我会在控制台中收到此错误:
Uncaught TypeError: Cannot read property 'status' of null
为什么会发生这种情况?
我忘记包含这个关键信息:
function fail ($message){
die(json_encode(array('status'=>'fail', 'message'=>$message)));
}
function success ($message){
die(json_encode(array('status'=>'success', 'message'=>$message)));
这会将消息发送回 jQuery 中的 AJAX 函数。看起来在我使用方法 #2 提交表单后,成功/失败消息被清空。
I have tried to different ways to clear a form:
<form action="service.php" id="addRunner" name="addRunner" method="post">
First Name: <input type="text" name="txtFirstName" id="txtFirstName" /><br />
Last Name: <input type="text" name="txtLastName" id="txtLastName" /><br />
Gender: <select id="ddlGender" name="ddlGender"><option value="">--Please Select--</option>
<option value="f">Female</option>
<option value="m">Male</option>
</select><br />
Finish Time:
<input type="text" name="txtMinutes" id="txtMinutes" size="10" maxlength="2">(Minutes)
<input type="text" name="txtSeconds" id="txtSeconds" size="10" maxlength="2">(Seconds)
<br />
<button type="submit" name="btnSave" id="btnSave">Add Runner</button>
<input type="hidden" name="action" value="addRunner" id="action">
</form>
jQuery #1:
function clearInputs(){
$("#txtFirstName").val('');
$("#txtLastName").val('');
$("#ddlGender").val('');
$("#txtMinutes").val('');
$("#txtSeconds").val('');
}
This works perfectly.
jQuery #2:
function clearInputs(data){
$("#addRunner :input").each(function(){
$(this).val('');
});
This clears the form but does not let me submit any more any information to it. I try and click the button again and it does nothing.
Here's the button click handler:
$("#btnSave").click(function(){
var data = $("#addRunner :input").serializeArray();
$.post($("#addRunner").attr('action'), data, function(json){
if (json.status == "fail"){
alert(json.message);
}
if (json.status == "success"){
alert(json.message);
clearInputs();
}
}, "json");
});
PHP Post code:
<?php
if($_POST){
if ($_POST['action'] == 'addRunner') {
$fname = htmlspecialchars($_POST['txtFirstName']);
$lname = htmlspecialchars($_POST['txtLastName']);
$gender = htmlspecialchars($_POST['ddlGender']);
$minutes = htmlspecialchars($_POST['txtMinutes']);
$seconds = htmlspecialchars($_POST['txtSeconds']);
if(preg_match('/[^\w\s]/i', $fname) || preg_match('/[^\w\s]/i', $lname)) {
fail('Invalid name provided.');
}
if( empty($fname) || empty($lname) ) {
fail('Please enter a first and last name.');
}
if( empty($gender) ) {
fail('Please select a gender.');
}
if( empty($minutes) || empty($seconds) ) {
fail('Please enter minutes and seconds.');
}
$time = $minutes.":".$seconds;
$query = "INSERT INTO runners SET first_name='$fname', last_name='$lname', gender='$gender', finish_time='$time'";
$result = db_connection($query);
if ($result) {
$msg = "Runner: ".$fname." ".$lname." added successfully" ;
success($msg);
} else {
fail('Insert failed.');
}
exit;
}
}
If I use jQuery method #2, I get this error in the console:
Uncaught TypeError: Cannot read property 'status' of null
Why does this happen?
I forgot to include this key information:
function fail ($message){
die(json_encode(array('status'=>'fail', 'message'=>$message)));
}
function success ($message){
die(json_encode(array('status'=>'success', 'message'=>$message)));
This sends the message back to the AJAX function in jQuery. It looks like after I submit the form once using method #2 the success/fail messages are blanked out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以尝试
输入不是选择器,因此您不需要
:
还没有用你的代码测试过。只是一个快速猜测!
You may try
Inputs are no selectors, so you do not need the
:
Haven't tested it with your code. Just a fast guess!
我知道那是什么了!当我使用each()方法清除字段时,它也清除了php需要运行的隐藏字段:
我在选择上使用了:not()来阻止它清除隐藏字段。
I figured out what it was! When I cleared the fields using the each() method, it also cleared the hidden field which the php needed to run:
I used the :not() on the selection to stop it from clearing the hidden field.
演示:http://jsfiddle.net/xavi3r/D3prt/
原始答案:使用 jQuery 重置多阶段表单
Mike 的建议(来自评论)以保持复选框和选择完好无损!
警告:如果您要创建元素(因此它们不在 dom 中),请将
:hidden
替换为[type=hidden]
或所有字段都将被忽略!Demo : http://jsfiddle.net/xavi3r/D3prt/
Original Answer: Resetting a multi-stage form with jQuery
Mike's suggestion (from the comments) to keep checkbox and selects intact!
Warning: If you're creating elements (so they're not in the dom), replace
:hidden
with[type=hidden]
or all fields will be ignored!我建议使用好的旧 JavaScript:
I'd recomment using good old javascript:
进行了一些搜索和阅读以找到适合我的情况的方法,在表单提交时,运行ajax到远程php脚本,在成功/失败时通知用户,在完全清除表单时。
我有一些默认值,所有其他方法都涉及 .val('') ,因此不会重置而是清除表单。
我也通过向表单添加一个重置按钮来实现此目的,该按钮的 id 为
myform
:这对我来说在重置表单方面得到了正确的结果,哦,不要忘记
停止表单提交在浏览器中,就像我一样:)。
问候
杰克
Took some searching and reading to find a method that suited my situation, on form submit, run ajax to a remote php script, on success/failure inform user, on complete clear the form.
I had some default values, all other methods involved .val('') thereby not resetting but clearing the form.
I got this too work by adding a reset button to the form, which had an id of
myform
:This for me had the correct outcome on resetting the form, oh and dont forget the
to stop the form submitting in browser, like I did :).
Regards
Jacko