使用变量更改选择框的选定值以指定选择框

时间:2014-01-16 04:05:16

标签: javascript jquery variables drop-down-menu

我知道我可以获得所选的值,如:

var selectVal = $('#mainIssueType: selected').val();

但是,如何将变量作为选择框ID传递给同一个人?

我尝试了什么:

var selectVal = $('#'+element.id+' :selected').val();

var selectVal = $(element+' :selected').val();

var selectVal = $([element]+' :selected').val();

完整功能:

$(function(){

   $('select').on( 'change', function( element ){
       $('#'+this.id).nextAll('select').remove();
        //get current selected option
        var selectVal = $(element+' :selected').val(); 
            //                  ^^ this is the problem
        //create a new select box and add to branchDiv
        var sel = $('<select>').appendTo('#branchDiv');
        //give the new element an id matching 
        //the selected value from the previous element
        sel.attr('id',selectVal);
        //set the select box's options using the values 
        //from the "selectVal" object within the "tree" object
        $(tree[selectVal]).each(function() {
            sel.append($("<option>").attr('value',this.val).text(this.text));
        }); 
    });

});

3 个答案:

答案 0 :(得分:1)

如果要使用event参数来检索selected选项的值,则必须将其target属性传递给Jquery object < / p>

尝试,

var selectVal = $(element.target).find(':selected').val(); 

或者简单地说,

var selectVal = $(this).find(':selected').val(); 

答案 1 :(得分:1)

这不起作用,因为您的案例中的element引用select元素而不是option,您想要:

var selectVal = $(this).find('option:selected').val();

答案 2 :(得分:0)

试试这个http://jsfiddle.net/8nhmU/20/

<select id="selDemo">
    <option value="1">Hi</option>
    <option value="2">Hifds</option>
    <option value="3">Hifsdf</option>
    <option value="4">Hids</option>
</select>

脚本:

$(document).ready(function() {
    $('#selDemo').change(function(){
    alert($('#selDemo').val());
    });
});
相关问题