Home > Mobile >  How to found or select pre selection (selected) option of select element in HTML using pure Javascri
How to found or select pre selection (selected) option of select element in HTML using pure Javascri

Time:11-21

Wanted to reset back to selected option once user click's reset or cancel certain form step in scenario

<button>Reset</button>
    <select>
      <option>1</option>
      <option>2</option>  
      <option>3</option>
    </select>
    
    <select >
      <option>a</option>
      <option >b</option>
      <option selected>c</option>
    </select>

CodePudding user response:

Here's a way to keep a history of the choices and allow rolling back the value for each click of the reset button...

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>Reset</button>
<select>
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>

<select >
  <option>a</option>
  <option>b</option>
  <option selected>c</option>
</select>

CodePudding user response:

Here is the answer, I found to the question I have.

document.querySelector('.jsPaymentStatusOptions option[selected]').index // find the selected option and its index value, in my case it returns 3
document.querySelector('.jsPaymentStatusOptions').selectedIndex = 3 // then set that index value to the select selectedIndex property it works.

self discovered from another thread, where answer suggested to use like option:checked (but which gives user changed current selected option in return):

document.querySelector('.jsPaymentStatusOptions option:checked')

What I want to achieve is this: https://codepen.io/tortoisefeel/pen/MWXrQQe (jQuery Way)

here is pure Javascript way: https://codepen.io/tortoisefeel/pen/MWXrQxJ

resetting select back to last selection option once user don't take action if the selection is in the view of page. Hope this helps out to someone in search. Thanks for reading.

  • Related