动态设置选项

时间:2016-07-04 15:46:03

标签: javascript jquery

如何设置动态选择的选项值?我已经尝试了相同的,

protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    if (e.CommandName == "h")
    {
        Button btn = (Button)(e.CommandSource);
        if(btn.Text == "hide")
        {
           btn.Text = "unhide";
           //Do additional work here, when unhiding.
        }
        else
        {
           btn.Text = "hide";
           //Do additional work here, when hiding.
        }

    }
}

3 个答案:

答案 0 :(得分:2)

试试这个:

function editFromDB(optionVal){
    $.get("/myEnd",function(myData) {                   
       var s = $('<select id="' + optVal + '" name="selectName" ></select>');
       $(myData).each(function(iter,element){
            var op = $('<option>');
            ...
            if(elem.name == optVal)
                op.attr('selected','selected');
            s.append(op);

       });
      //$("#" + optVal).val(optVal);

答案 1 :(得分:2)

只需添加&#34;选中:true&#34;

For i As Integer = 2 To 10
    xlWorkSheet.Range("E" & i).Value = rNum.Next()
Next i

使用它的两种方法:

    $('<option></option>', {
                    value:"lol2", 
                    text: "yo2",
                    selected : true
                }).appendTo($("#test")); 

或者你可以这样做:

$(myData).each(function(iter, element){
if (your_condition_for_selected) {
            $('<option></option>', {
                value: elem.name, 
                text: elem.name,
                selected : true
            }).appendTo(s); 
        });
} else {
 $('<option></option>', {
                value: elem.name, 
                text: elem.name
            }).appendTo(s); 
        });
}

答案 2 :(得分:1)

首先,您需要将已创建的select附加到DOM,然后才能在其上设置val()

其次,您可以直接使用s变量中的jQuery对象,而无需将id选择器混合在一起。试试这个:

function editFromDB(optVal) {
    $.get("/myEnd", function(myData) {                  
        var $s = $('<select id="' + optVal + '" name="selectName" ></select>').appendTo('body'); // append here as needed
        $.each(myData, function(i, element){
            $('<option></option>', {
                value: elem.name, 
                text: elem.name
            }).appendTo($s); 
        });    
        $s.val(optVal);
    });
}

Working example