使用下拉选项将文本放入div

时间:2011-09-26 03:49:27

标签: jquery html

我有以下代码,但它不起作用。我想将所选文本放入我的选定位置div。有任何想法吗?谢谢!

    <select name='available_locations' class='select-location'>
        <option value='Germany'>Germany</option>
        <option value='Venice'>Venice</option>
        <option value='Spain'>Spain</option>
    </select>

    <div id='selected-locations'>

    </div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type='text/javascript'>
    $(document).ready(function() {

        $('.select-location').change(function(){

                        var location = $( this ).attr( 'value' );
                        alert( location );
                        //new_text = $('#selected-locations').val() + location;
                        $('div.selected-locations').text( location );


        });

    });

</script>

3 个答案:

答案 0 :(得分:2)

您需要阅读css selectorsjQuery selectors

$('div.selected-locations').text( location );

应该是

$('div#selected-locations').text( location );

OR

<div id='selected-locations'>

</div>

应该是

<div class='selected-locations'>

</div>

答案 1 :(得分:0)

你可以这样做

$('.select-location').change(function(){
    var location = $('.select-location option:selected').val();
    $('div#selected-locations').text(location);
});

工作示例: http://jsfiddle.net/jasongennaro/F3A62/

您需要使用代码更改一些内容:

  1. $('div.selected-locations')更改为$('div#selected-locations') ...期间以哈希
  2. 使用option:selected
  3. 使用val()

答案 2 :(得分:0)

使用
    $('#selected-locations')。text(location);  您需要使用#作为selected-locations是一个id而不是一个css类。