JQuery - Form Reset - Exclude “Select” box

吃可爱长大的小学妹 提交于 2019-12-12 08:02:05

问题


All,

I can reset all my form elements using the following JQuery Syntax:

('#myform')[0].reset();

How can I modify this to exclude the reset of "select box" values?

Thanks


回答1:


To everyone..

the reset function does not set everything to '' (empty string)

it reset to their initial values .. (stored in the value attribute, or selected option etc..)

If you want to maintain the default reset features then you should

  1. get all the <select> elements
  2. get their currently selected values
  3. reset the form as you currently do
  4. re-set the selected

example:

<script type="text/javascript">
  $(document).ready(
  function(){
   $("#resetbutton").click(
    function(){
     var values = [];
     var selected = $("select").each(
      function(){
       values.push( $(this).val());
       });
     this.form.reset();
     for (i=0;i<selected.length;i++)
      $(selected[i]).val(values[i]);
    });
    }
  );
 </script>



回答2:


That's not jQuery, it's native javascript. [0] brings out the actual DOM element, so it's the same as:

document.getElementById('myform').reset();

reset() is a built-in browser implementation that resets the entire form. If you need to reset individual form types, try something like:

$('#myform :text').val('');

You can see all form selectors here: http://docs.jquery.com/Selectors




回答3:


You can do a fake reset by setting the values to an empty string and resetting the checkboxes using David's answer (or this more complete one). You could also try storing each select element's value before resetting the form and then restore the values after:

var myform = $('#myform');
var selects = $('select', myform);

// Store each current value
selects.each(function() {
    $(this).data('previous', $(this).val()); 
});

myform[0].reset();

// Restore the values
selects.each(function() {
    $(this).val($(this).data('previous')); 
});



回答4:


For whatever reason, David's right-on answer error'd my Google Chrome js. It's saying:

Uncaught TypeError: Property 'reset' of object # is not a function

...so I decided to try a slightly different solution:

  • Give native browser reset buttons attributes "hidden" and set "id":

<input id="resetbutton" type="reset" style="visibility:hidden;" name="reset" value="reset" />

  • Initiate JQuery "click" event on reset button from clicking link:

<a href="#" onclick="$('#resetbutton').click();">Reset</a>



来源:https://stackoverflow.com/questions/2002957/jquery-form-reset-exclude-select-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!