I had used the jQuery form validation plugin to validate a form with jQuery ‘rules’ in one of my Ruby on Rails projects. It worked fine but I was stuck when it comes to display a DIV block on ‘onchange’ event of selectbox. The ‘onchange’ event execute an event(s) but for single <option> as a default.

I had a form with two <option> where their value was NULL. I had to create a validation for both NULL values <option>.

Because ‘onclick’ event on <option> doesn’t work in Internet Explorer, I had to use a different method. I was looking for a simple solution. Due to time limit I skipped to google more and focused on the properties of the field. And found a solution! The ‘childNodes[]’ property was there to check the length of <select> means how many <option> are there in <select> field!

Here are those functions I had created:

function showElement(blockID, field){
  var getID = document.getElementById(blockID);
  if(getID.style.display == 'none' && field.value != ''){
    getID.style.display = 'block';

function hideElement(blockID, noneOption){
  var getID = document.getElementById(blockID);
  var none = document.getElementById(noneOption);
  if(none.childNodes[0].selected && getID.style.display == 'block'){
    getID.style.display = 'none';

Then call these functions on <select> field with ‘onchange’ event.

<select id="shipping" onchange="showElement('add_location_div', 'shipping'); hideElement('add_location_div', 'shipping');">
  <option value="" selected="selected">None</option>
  <option value="">Add Address</option>
  <option value="location1">Location 1</option>

Where ‘add_location_div’ is a DIV which I wanted to display.

Here are some reference to read more…

Similar Posts