« 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   English (AU) 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

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,

Code:

<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>

Trackback address for this post

This is a captcha-picture. It is used to prevent mass-access by robots.
Please enter the characters from the image above. (case insensitive)

3 comments

Comment from: Rahul S. Gupta [Visitor]
Rahul S. Guptaawesome,

Thanks!!!
04/08/09 @ 13:14
Comment from: Mahesh [Visitor] Email
Maheshvery Good tip
29/04/10 @ 10:47
Comment from: Emile [Visitor]
EmileYou might want to use the "onfocus" event for setting the cache value. Onclick doesn't work when using a keyboard.
05/07/11 @ 11:50

Leave a comment


Your email address will not be revealed on this site.
(Line breaks become <br />)
(For my next comment on this site)
(Allow users to contact me through a message form -- Your email will not be revealed!)
This is a captcha-picture. It is used to prevent mass-access by robots.
Please enter the characters from the image above. (case insensitive)
February 2012
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        
Brinley Ang

Brinley Ang is a sysadmin, web dev, 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
© 2012 - Brinley Ang
Valid xhtml