Ivan Castellanos
Ivan Castellanos

Reputation: 57

jQuery: change a css value if a option is selected

I'm trying to make an option dropdown menu and I got stuck when I try to show a textbox if the option 'other' is selected.

there's what I have:

<span id="con-country"><label for="country">Country: </label>
<select name="country" required="required">
<option value="usa">United States</option>
<option value="uk">United Kingdom</option>
<option id="other" value="other">Other</option>
</select>
</span>

<span id="con-specify">
<label for="specify">Specify: </label>
<input type="text" name="specify" id="c-specify" required="required"></input>
</span>

CSS:

#con-specify{
    margin-left: 50px;
    display: none;
}

Simple huh?, the problem is that I don't know how to do the code in jQuery

So, if the user select other in the menu, then the textbox should appear, how can I do that?

Upvotes: 0

Views: 1590

Answers (3)

Sun
Sun

Reputation: 1

You will want to add a jQuery link in the head of the html:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">

The dropdown menu should have an id (ie: country).

Then your javascript would look something like this:

    window.onload = function() {
      $('#con-specify').hide();

      $('#country').change(function(){
        if($(this).val() == 'other') {
            $('#con-specify').show();
        } else {
            $('#con-specify').hide();
        }
      });
    };

Upvotes: 0

Steve
Steve

Reputation: 8640

If you already use jQuery, simply use $('#con-specify').show() and $('#con-specify').hide()

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388336

Try

//dom ready handler
jQuery(function($){
    //change event handler for the select
    $('select[name="country"]').change(function(){
        //set the visibility of the specify element based on the value of select
        $('#con-specify').toggle(this.value == 'other')
    }).change();//fire the change event so that the initial visibility is set
})

Demo: Fiddle

Read more about each of the methods in http://api.jquery.com/

Upvotes: 1

Related Questions