jQuery:清除表单输入

发布于 2024-12-10 00:08:06 字数 3430 浏览 0 评论 0原文

我尝试过不同的方法来清除表单:

<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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

一影成城 2024-12-17 00:08:07

您可以尝试

$("#addRunner input").each(function(){ ... });

输入不是选择器,因此您不需要 :
还没有用你的代码测试过。只是一个快速猜测!

You may try

$("#addRunner input").each(function(){ ... });

Inputs are no selectors, so you do not need the :
Haven't tested it with your code. Just a fast guess!

娇女薄笑 2024-12-17 00:08:07

我知道那是什么了!当我使用each()方法清除字段时,它也清除了php需要运行的隐藏字段:

if ($_POST['action'] == 'addRunner') 

我在选择上使用了: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:

if ($_POST['action'] == 'addRunner') 

I used the :not() on the selection to stop it from clearing the hidden field.

最冷一天 2024-12-17 00:08:06

演示:http://jsfiddle.net/xavi3r/D3prt/

$(':input','#myform')
  .not(':button, :submit, :reset, :hidden')
  .val('')
  .removeAttr('checked')
  .removeAttr('selected');

原始答案:使用 jQuery 重置多阶段表单


Mike 的建议(来自评论)以保持复选框和选择完好无损!

警告:如果您要创建元素(因此它们不在 dom 中),请将 :hidden 替换为 [type=hidden] 或所有字段都将被忽略!

$(':input','#myform')
  .removeAttr('checked')
  .removeAttr('selected')
  .not(':button, :submit, :reset, :hidden, :radio, :checkbox')
  .val('');

Demo : http://jsfiddle.net/xavi3r/D3prt/

$(':input','#myform')
  .not(':button, :submit, :reset, :hidden')
  .val('')
  .removeAttr('checked')
  .removeAttr('selected');

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!

$(':input','#myform')
  .removeAttr('checked')
  .removeAttr('selected')
  .not(':button, :submit, :reset, :hidden, :radio, :checkbox')
  .val('');
成熟的代价 2024-12-17 00:08:06

我建议使用好的旧 JavaScript:

document.getElementById("addRunner").reset();

I'd recomment using good old javascript:

document.getElementById("addRunner").reset();
鲜血染红嫁衣 2024-12-17 00:08:06

进行了一些搜索和阅读以找到适合我的情况的方法,在表单提交时,运行ajax到远程php脚本,在成功/失败时通知用户,在完全清除表单时。

我有一些默认值,所有其他方法都涉及 .val('') ,因此不会重置而是清除表单。

我也通过向表单添加一个重置按钮来实现此目的,该按钮的 id 为 myform

$("#myform > input[type=reset]").trigger('click');

这对我来说在重置表单方面得到了正确的结果,哦,不要忘记

event.preventDefault();

停止表单提交在浏览器中,就像我一样:)。

问候

杰克

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:

$("#myform > input[type=reset]").trigger('click');

This for me had the correct outcome on resetting the form, oh and dont forget the

event.preventDefault();

to stop the form submitting in browser, like I did :).

Regards

Jacko

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文