RationalRabbit
RationalRabbit

Reputation: 1067

Clearing drop-down select value on page exit so back button return may reselect

I am, basically, answering the question here, but perhaps someone has another idea. You can use an onpopstate function, but I find this much simpler to deal with and cross-browser compatible, even with old browsers.

I have a drop-down select box that is populated by a database query. In this case, it has only found one relevant city. Selecting that city, which takes the user to another page, then pressing the Back button, returns the user to the page with the selection still in the selected state, which prevents it from being selected again, unless another selection is made first. So I added an onClick event to change the Selected default before leaving the page.

HTML

<div>
    <select class="DropList"  name="CitySelect" id="CitySelect"
        onchange="if(options[selectedIndex].value){location = options[selectedIndex].value}"
        onclick="GetSelect()">
        <option value="" selected>Select City</option>
        <option value="city.php?s=Montana&cn=Yellowstone&CalNav=0&c=Billings">Billings</option>
    </select>
</div>

JavaScript

<script type="text/javascript">
    function GetSelect()
    {
        document.getElementById('CitySelect').value = "";
    }
</script>

Upvotes: 3

Views: 2801

Answers (1)

ehrencrona
ehrencrona

Reputation: 7002

Listening for the click event is not ideal for a couple of reasons:

  • It's triggered when you click the select to open it, not when you actually select an option. So your code clears the value when you open the select which results in a bit of jerkiness.
  • It's not triggered if you use the keyboard to select a value.

So I'd instead suggest using the blur event:

$('#CitySelect').on('blur', (e) => (e.target.value = ''));

Immediately after selecting the value, the select field will still have the new value but as soon as you leave the field ("blur" it), the value will reset.

Check out this fiddle

Upvotes: 1

Related Questions