Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Clearing Form Inputs

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.

like image 327
Charles Blackwell Avatar asked Oct 17 '11 10:10

Charles Blackwell


People also ask

How do I clear all inputs in a form?

To clear all the input in an HTML form, use the <input> tag with the type attribute as reset.

How do I clear data from a form?

Form reset() Method The reset() method resets the values of all elements in a form (same as clicking the Reset button). Tip: Use the submit() method to submit the form.

How do you clear input value after submitting?

To clear an input field after submitting:Add a click event listener to a button. When the button is clicked, set the input field's value to an empty string. Setting the field's value to an empty string resets the input.


2 Answers

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(''); 
like image 116
Xavier Avatar answered Sep 18 '22 13:09

Xavier


I'd recomment using good old javascript:

document.getElementById("addRunner").reset(); 
like image 34
jwaern Avatar answered Sep 20 '22 13:09

jwaern