Reputation: 718
I'm trying to have a field appear in a form for when the user selects an option from a dropdown - i.e. if they select "Other" from a dropdown, a field appears below the dropdown saying "Please specify". I can't seem to get it to work at all - the "please specify" field appears visible all the time. Where am I going wrong? Thanks!
<script>
$(function(){
$("#pref-select").change(function(){
if ($("#pref-select").val()=="Other"){
$("#other-pref").show();
} 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_preference %><br />
<%= f.text_area :other_pref %>
</div>
Upvotes: 0
Views: 4500
Reputation: 1191
I never tried but have you ever heard of dependent-fields-rails gem?
Upvotes: 1
Reputation: 215
You can do it like this: http://jsfiddle.net/vooboo13/RK97r/1/
You give the fields you don't want to show css values of display:none;
You then use jQuery to watch for a certain value and display it if it's that value.
HTML:
Select "fiat", and see magic happen
<form action="" id="cars">
<select name="cars" id="car_selector">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<p> </p>
<label class="hidden_option">Why would you DO that?</label>
<input type="text" name="reason" class="hidden_option" />
</form>
JS:
$(document).ready(function(){
$("#car_selector").change(function(){
if($("#car_selector").val() == "fiat"){
$(".hidden_option").fadeIn('fast');
}
});
});
CSS:
.hidden_option{
display: none;
}
Upvotes: 8