Jquery attach show event to select option

Posted by John on Stack Overflow See other posts from Stack Overflow or by John
Published on 2010-03-18T10:25:51Z Indexed on 2010/03/18 10:31 UTC
Read the original article Hit count: 233

Filed under:
|

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

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about html-form