search

Home  >  Q&A  >  body text

How can I use Javascript in HTML to provide a form's reset or cancel button with the functionality to reselect the selected option and keep it in the same state?

After the user makes some selection changes on the selection element, when the user wants to cancel or reset the form, the system-selected options need to be displayed to the user. (The focus is to reset the form selection element and return to the default selected option value in the view when canceling or resetting the form)

<button>重置</button>
    <select>
      <option>1</option>
      <option>2</option>  
      <option>3</option>
    </select>
    
    <select class="jbselect">
      <option>a</option>
      <option >b</option>
      <option selected>c</option>
    </select>
P粉726133917P粉726133917476 days ago597

reply all(1)I'll reply

  • P粉842215006

    P粉8422150062023-09-11 18:54:50

    This is a way to preserve selection history and allow values ​​to be rolled back on each reset button click...

    let history = []
    $(function() {
      $('.jbselect').change(function() {
        history.push($(this).val());
      })
      // start it off
      history.push($('.jbselect').val());
    })
    
    $("button").click(function() {
      if (history.length == 1) return
      // remove latest value
      history.splice(-1, 1)
      $('.jbselect').val(history.at(-1))
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button>重置</button>
    <select>
      <option>1</option>
      <option>2</option>
      <option>3</option>
    </select>
    
    <select class="jbselect">
      <option>a</option>
      <option>b</option>
      <option selected>c</option>
    </select>

    reply
    0
  • Cancelreply