I’ve got a form where if the user selects “Other” from a dropdown, a field appears below saying “Other – please specify”. However, it isn’t quite working. If I set display:none for the “please specify” field, then when the form is saved and the user goes back in to edit it, all they see is the select box, and not the “please specify” field.
I know why this is happening – it is because the jQuery is waiting for the select box to be changed by the user before the show event fires.
However, if I remove the display:none from the CSS, then when the user first displays the form, they see the select box, and the “please specify” field, regardless of what is displayed in the select box. What can I do to fix this? I could have the “if” block of the code execute on the page load as well, but don’t know how to do this? Thanks!!
<script>
$(function(){
$("#pref_select").change(function(){
if ($("#pref_select").val()=="Other"){
$("#other-pref").show(500);
} else {
$("#other-pref").hide();
}
})
})
</script>
<div class="field">
<%= f.label :pref %><br />
<%= f.select :pref, ["", "1", "2", "Other"], {:id => "pref_select"} %>
</div>
<div class="field" id="other-pref">
<%= f.label "Other - please specify" %><br />
<%= f.text_area :other_pref %>
</div>
If you want to trigger the check on page load you to trigger the change event. You bound the change event but your check will only occur once it’s been triggered. So to get your desired affect you need to trigger change() on page load