How to reset (clear) form through JavaScript?

2019-01-02 18:37发布

问题:

I have tried $("#client.frm").reset(); but it is not working.So how to reset form via jQuery?

回答1:

form.reset() is a DOM element method (not one on the jQuery object), so you need:

$("#client.frm")[0].reset();
//faster version:
$("#client")[0].reset();

Or without jQuery:

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


回答2:

You can simply do:

$("#client.frm").trigger('reset')



回答3:

Pure JS solution is as follows:

function clearForm(myFormElement) {

  var elements = myFormElement.elements;

  myFormElement.reset();

  for(i=0; i<elements.length; i++) {

  field_type = elements[i].type.toLowerCase();

  switch(field_type) {

    case "text":
    case "password":
    case "textarea":
          case "hidden":

      elements[i].value = "";
      break;

    case "radio":
    case "checkbox":
        if (elements[i].checked) {
          elements[i].checked = false;
      }
      break;

    case "select-one":
    case "select-multi":
                elements[i].selectedIndex = -1;
      break;

    default:
      break;
  }
    }
}


回答4:

Reset (Clear) Form throught Javascript & jQuery:

Example Javascript:

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

Example jQuery:

You may try using trigger() Reference Link

$('#client.frm').trigger("reset");


回答5:

Note, function form.reset() will not work if some input tag in the form have attribute name='reset'



回答6:

,reset() method does not clear the default values and checkbox field and there are many more issues.

In order to completely reset check the below link -

http://www.javascript-coder.com/javascript-form/javascript-reset-form.htm



回答7:

Try this :

$('#resetBtn').on('click', function(e){
    e.preventDefault();
    $("#myform")[0].reset.click();
}


回答8:

Use JavaScript function reset():

document.forms["frm_id"].reset();


回答9:

Try this code. A complete solution for your answer.

    <!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(":reset").css("background-color", "red");
});
</script>
</head>
<body>

<form action="">
  Name: <input type="text" name="user"><br>
  Password: <input type="password" name="password"><br>
  <button type="button">Useless Button</button>
  <input type="button" value="Another useless button"><br>
  <input type="reset" value="Reset">
  <input type="submit" value="Submit"><br>
</form>

</body>
</html>


回答10:

Clear the form as follows

document.forms[0].reset();

You can simply clear the form elements within the group. by using this forms[0].



回答11:

You could use the following:

$('[element]').trigger('reset')


标签: