问题
I'm having a very difficult time trying to figure out how to make my code function properly. I currently have a div that is hidden on load and changes once a selection is made from a dropbox.
Once the selection (United States) is made from the dropbox, the hidden div appears, and the user and continue filling out the form.
My issue arrises when the user saves the form, and then comes back to that page--> the div is no longer visible (I believe that is because its inherent display value is set to "none;"). The user must once again select the proper value from the drop down (United States) in order to view the div.
I want to know how I can make the div visible on a page refresh if the correct value is in the dropbox. I am programming in HAML and all the option values (United States, International) are located in the constants.rb file.
I believe this is possible to achieve either via cookies (which I'd like to avoid if possible) or through some sort of jscript/jquery validation on page load... unfortunately I'm not at all familiar with either of those things, so I kindly ask for any help.
I sincerely appreciate you taking the time to help me out. Thank you!
HAML code:
= f.select :location, LOCATIONS, {}, :onChange => "showStates(this)", :prompt => true
#states_div{:style => "display:none;"}
%div{:class => "label_leftalign field"}
= f.label :state, "State"
= f.select :state, STATES, :prompt => true
Javascript:
function showStates(obj)
{
if(obj[obj.selectedIndex].value == 'United States')
{
document.getElementById('states_div').style.display = 'block';
}
else
{
document.getElementById('states_div').style.display = 'none';
}
}
回答1:
You can achieve this by just running showStates(this) on page load. Just add this to the bottom of your template:
:javascript
window.onload = function() {
select_location = document.getElementById('<id of select tag generated for location>')
if(select_location[select_location.selectedIndex].value == 'United States')
{
document.getElementById('states_div').style.display = 'block';
}
else
{
document.getElementById('states_div').style.display = 'none';
}
};
Then if United States is present in the form it will display it.
来源:https://stackoverflow.com/questions/6937328/show-hidden-divs-on-refresh