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

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.

Follow up:

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)

1 comment

  1. Permanent link for this comment Rahul S. Gupta said on
    awesome,

    Thanks!!!

Leave a comment


Your email address will not be revealed on this site.

Your URL will be displayed.
(Line breaks become <br />)
(Name, email & website)
(Allow users to contact you 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)
March 2010
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 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
XML Feeds
home | portfolio | blog | contact
© 2010 - Brinley Ang
Valid xhtml