Javascript how to run same function onLoad and onChange

I have a form that has many favorites menus, most of them are Yes / No, and depending on the option I choose, I show / hide some additional options. One of the selected menus is the following:

<td><%= :CBIAvailable, ['Yes' , 'No'],{}, {:id=>"cbi_available_id", :class=>"cbi_available_class", :onChange=>"showHideOptions('cbi_available_id','cbi_options_id')", :onLoad=>"showHideOptions('cbi_available_id','cbi_options_id')"} %></td>


When I switch from "Yes" to "No" or vice versa, the showHideOptions javascript functions are called as expected, but I cannot call this function on form reload.

Can anyone tell me what I am doing wrong?



<script language="javascript" type="text/javascript">
function showHideOptions(selectorId,optionsId) {
  if (document.getElementById) {
    var selector = document.getElementById(selectorId);
    var options = document.getElementById(optionsId);
    if (selector.value == 'Yes') { = 'block';
        return false;
    } else { = 'none';
        return false;

window.onLoad = showHideOptions('cbi_available_id','cbi_options_id');



source to share

2 answers

function yourFunction(){

    //get that select element and evaluate value
    //do you change stuff here

window.onload = yourFunction;   //this gets fired on load

//"select" is your element, 
//fetched by methods like document.getElementById();

select.onchange = yourFunction; //this gets fired on change

//you can also use attachEvent (IE) or addEventListener (Others)


here's a working demo :

<select id="testSelect">
    <option value="yes">YES</option>
    <option value="no">NO</option>

function getOption() {

var select = document.getElementById('testSelect');
select.onchange = getOption;
window.onload = getOption;




This can happen when you receive a postback from a remote server and your response has no <script type="javascript">... yourfunction()...</script>


Every time you get a new response you have to send the script and exacute it or add it to your html event handler.

Another solution is to use jQuery and use . live () event. This event adds dynamic behavior to your html. I highly recommend using jQuery live because it is one of the most commonly used libraries in production.


<script type="text/javascript" src="path_to_jquery.js"></script>
<script type="text/javascript">
function showHideOptions(id1,id2){
    //Your code
$(document).ready(function() {
   //This function waits for DOM load
   //execute your function for first time
   //This selector you have to modify or show us generated html to
   // choose the best selector for this purpose
        //This will fire change event of html class="cbi_available_class"




All Articles