DMH
DMH

Reputation: 2809

Hide field based on value of select box

I am using Rails 3.1 and I am rendering a form. I have an additional field that I only want to be shown if the user selects 'Other' in the select field. I currently have it showing the additional field once other is selected, however if the user saves their choice on page reload it does not load the additional field again even though the select box is other.

Here is the jQuery

$(document).ready(function() {
    $('#user_gender_custom').hide();
    $("#user_gender").change(function() {
        if ($("#user_gender").val() == "custom") $("#user_gender_custom").show();
        else $("#user_gender_custom").hide();
    });
});   

If I remove the initial $('#user_gender_custom').hide(); it does always loads the additional field on a page load even if the select box value is not Other.

Can anyone show me how to get this working correctly? Help would be very much appreciated.

Upvotes: 0

Views: 118

Answers (2)

The Ancient
The Ancient

Reputation: 380

If the only problem is the initial load (the field is always shown), maybe it makes sense to do something like that:

function toggle_custom() {
  if ($("#user_gender").val()=="custom")
    $("#user_gender_custom").show();
  else
    $("#user_gender_custom").hide();
}

$(function() { 
  toggle_custom();
  $("#user_gender").change(function() {
    toggle_custom();
  });
});

Upvotes: 1

guradio
guradio

Reputation: 15565

$(document).ready(function() {
    $("#user_gender").val("custom")
    $('#user_gender_custom').hide();
    
    $("#user_gender").change(function() {
        if ($("#user_gender option:selected").val() == "custom") $("#user_gender_custom").show();
        else $("#user_gender_custom").hide();
    });
  $("#user_gender").change();
});  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id='user_gender'>
  <option val=''></option>
  <option val=''>custom11</option>
<option val='custom'>custom</option>

</select>
<input type='text' id='user_gender_custom'/>

Please add on change manually. So that the change function will be call on load

Upvotes: 0

Related Questions