views:

13

answers:

1

I'm trying to display some text in a div named "msg_box" for each selected option. It works but not live. I have to refresh to see the result.

The js is..

$(function() {
switch ($('#my_options :selected').val()) {
case '1':
    $('.msg_box').html('You selected option one');
break;
case '2':
    $('.msg_box').html('You selected option two');
break;
}

});

the div where text should appear according to the selected option..

<div class="msg_box"></div>

and the form..

<select id="my_options">
  <option value="0">Select...</option>
  <option value="1">Something</option>
  <option value="2"> Something else </option>
</select>

Can someone please share how to change the html() dynamically?

A: 

You'll want to use a .change() event handler for the <select>:

Try it out: http://jsfiddle.net/mjNC3/2/

$(function() {
    $('#my_options').change(function() {
        var str = 'You selected option ';
        switch (this.value) {
        case '1':
            str += 'one';
            break;
        case '2':
            str += 'two';
            break;
        }
        $('.msg_box').html(str);
    });
});

patrick dw
Mate, that's brilliant! Thanks also for sharing jsFiddle! I didn't know about it :)
@user - Glad it worked. Yeah, jsFiddle is very cool. Hang around here and you'll see it used a lot. :o)
patrick dw