开发者

jQuery selected options in conditional statements

开发者 https://www.devze.com 2023-01-18 23:31 出处:网络
I\'m trying to display some text in a div named \"msg_box\" f开发者_C百科or each selected option. It works but not live. I have to refresh to see the result.

I'm trying to display some text in a div named "msg_box" f开发者_C百科or 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?


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);
    });
});

0

精彩评论

暂无评论...
验证码 换一张
取 消