How to reset (clear) form through JavaScript?

2019-01-02 17:56发布

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

11条回答
梦寄多情
2楼-- · 2019-01-02 18:36

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>
查看更多
荒废的爱情
3楼-- · 2019-01-02 18:38

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

查看更多
深知你不懂我心
4楼-- · 2019-01-02 18:42

Clear the form as follows

document.forms[0].reset();

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

查看更多
春风洒进眼中
5楼-- · 2019-01-02 18:43

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;
  }
    }
}
查看更多
何处买醉
6楼-- · 2019-01-02 18:44

Try this :

$('#resetBtn').on('click', function(e){
    e.preventDefault();
    $("#myform")[0].reset.click();
}
查看更多
登录 后发表回答