jQuery:清除表单输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7792320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:16:41  来源:igfitidea点击:

jQuery: Clearing Form Inputs

jqueryformsconsole

提问by Charles Blackwell

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:

jQuery #1:

function clearInputs(){
$("#txtFirstName").val('');
$("#txtLastName").val('');
$("#ddlGender").val('');
$("#txtMinutes").val('');
$("#txtSeconds").val('');
}

This works perfectly.

这完美地工作。

jQuery #2:

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邮政编码:

<?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:

如果我使用 jQuery 方法 #2,我会在控制台中收到此错误:

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.

这会将消息发送回 jQuery 中的 AJAX 函数。看起来在我使用方法 #2 提交表单后,成功/失败消息被清除。

回答by Xavier

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

演示: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

原答案:用 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 :hiddenwith [type=hidden]or all fields will be ignored!

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

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

回答by jwaern

I'd recomment using good old javascript:

我建议使用旧的 javascript:

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

回答by Hymano

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.

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

I had some default values, all other methods involved .val('') thereby not resetting but clearing the form.

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

I got this too work by adding a reset button to the form, which had an id of myform:

我通过在表单中​​添加一个重置按钮来解决这个问题,它的 id 为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

问候

Hymano

杰科

回答by madc

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!

输入不是选择器,因此您不需要尚未:使用您的代码对其进行测试。只是一个快速的猜测!

回答by Charles Blackwell

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:

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

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

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

我在选择上使用了 :not() 来阻止它清除隐藏字段。