views:

99

answers:

3

Hi, I have a select form element with 5 options. If option 2 is selected I want to display another form input box (this has a style of display:none initially). How can I attach an event to option 2 so that whenever it is selected the input box is shown otherwise it is hidden. I have this currently but this does not handle is option 2 is already selected when the page loads

$('#type').change(function(){
        var typeSelected = $(this).val();
        if (typeSelected == 2) {
            $('#extraInput').show();
        }
    });

I know I could add another bit of code which checks what is selected on page load but wondered if there was a neater way of doing this. Also something that could handle the hiding of the input box if option 2 is not selected at the start as currently I have just hard-coded style="display:none" onto the input box but I would prefer this to be dynamic.

Thanks

+2  A: 

What if you try $('#type').trigger('change'); on page load? Does that solve the problem?

$('#type').trigger('change');
$('#type').change(function(){
    var typeSelected = $(this).val();
    if (typeSelected == 2) {
        $('#extraInput').show();
    } else {
        $('#extraInput').hide();
    }
});
+4  A: 

You might wanna try :

  $('#type').change(function(){
            var typeSelected = $(this).val();
            if (typeSelected == 2) {
                $('#extraInput').show();
            }
            else{
            $('#extraInput').hide();
            }
        });

How does your html looks like <option>Option name</option> or

<option value="0">Option name</option>

Refer to my previous answer :

http://stackoverflow.com/questions/2446188/submit-form-to-2-different-action-page/2446212#2446212

You need to have option value in order to compare which option you selected.

c0mrade
<option value="0">Option name</option>
John
+2  A: 

your code must look like this: DEMO: http://jsbin.com/ezolu4/edit

$(function() {

      $('#type').change(function() {
            var typeSelected = $(this).val();

            if (typeSelected == 2) {
                $('#extraInput').fadeIn(200);
            } else {
          $('#extraInput').fadeOut(200);
          }
        }).change();
    });

Ops.. I have the solution for you!

aSeptik
thanks it worked. just a question, what is the purpose of $(function() { at the beginning of the code? Also is the .change(); at the end of the code just used to trigger a change on the type object automatically just the same as the trigger event in the above answer does?
John
$(function () {}); is just like DOM ready! $(document).reday(function(){});it tell the script that when page load must execute something!
aSeptik