javascript how to run the same function onLoad and onChange
26,760
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>
</select>
function getOption() {
alert('foo');
}
var select = document.getElementById('testSelect');
select.onchange = getOption;
window.onload = getOption;
Author by
rh4games
Updated on July 09, 2022Comments
-
rh4games almost 2 years
I have a form that has many select menus, most of them are Yes/No and depending on the selected option, I display/hide some advanced options. One of the select menus is the following:
<td><%= f.select :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 change from 'Yes' to 'No' or the opposite, showHideOptions javascript functions is called properly, but I can't have that function to be called when I reload the form.
Anyone can tell me what am I dong wrong?
Thanks
UPDATE
<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') { options.style.display = 'block'; return false; } else { options.style.display = 'none'; return false; } } window.onLoad = showHideOptions('cbi_available_id','cbi_options_id');