« Real Life Guitar Hero 4 World TourVmware Server 2.0 breaks keyboard mapping on Ubuntu 8.10 »

Undo a HTML select box selection

Javascript, 196 words   Bookmark and Share

When a select box requires on the fly validation, HTML and JavaScript doesn’t quite support any way of reverting to a previous choice if the validation fails. You cant trigger an onchange event without first updating the select box to a different value. On the other hand, onclick occurs before the choice is made.

If you set a “selected” tag within an option tag on page load, you can easily revert to a previous value by resetting the form or running reset() on the form. However this kinda makes the selected value pretty static.

The following example will firstly show the javascript code


<script type="text/javascript">

var selectList_cache; // Variable for remember previous choice

function validateList(val)
{
  if(isValid())
  {
     alert("Validated successfully!");
  }
  else
  {
     alert("Failed the validation so reverting");
     document.getElementById("selectList").value=selectList_cache;
  }
}
</script>

Followed by the HTML select box,


<select name="selectList" id="selectList" onclick="selectList_cache=this.value" onchange="validateList(this.value);return false">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>

December 2024
Mon Tue Wed Thu Fri Sat Sun
            1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31          
 << <   > >>
Brinley Ang

Brinley Ang is a software engineer, sysadmin, coder, geek boy, jedi knight fragger, caffine addict, deaf meloncholic and rockstar wannabe. Listens to the sex pistols and a wide assortment of heavy metal.

Make payments with PayPal - it's fast, free and secure!
Search
home | portfolio | blog | links | contact
© 2024 - Brinley Ang
Valid xhtml