0

コンボボックスにはいくつかの値があり、いくつかの値もあります。コンボボックスから1つの値を選択し、操作を行って、選択した値に戻ります(これらの値をセッションに設定します)。ここで、コンボ ボックスでセッション中の値を自動的に選択する必要があります。

以下の JavaScript に従っていますが、正常に動作しますが、既にコンボ ボックスにある値が重複して作成されます。

function addCombo() {
    var reportID = '<%=reportid%>';
    var reportName = '<%=reportname%>';

    var textb = document.getElementById("reportnames");

    var option = document.createElement("option");
    option.text = reportName;
    option.value = reportID;
    option.selected='selected';
    try {
        textb.add(option, null); //Standard
    }catch(error) {
        textb.add(option); // IE only
    }
    textb.value = "";
}

誰かが私を特定するのを手伝ってくれますか?

4

2 に答える 2

0

わかりました試してみてください:

function addCombo() {
    var reportID = 'aa';
    var reportName = 'aa';

    var textb = document.getElementById("reportnames");
    var option = document.createElement("option");

    if (hasValue(textb, reportID)) (function() {


        // selected attr remove
        for (var i=textb.options.length-1; i >= 0; i--) (function() {

            if (textb.options[i].selected == true) (function() {

                textb.options[i].removeAttribute("selected");
            }());
        }());

        option.text = reportName;
        option.value = reportID;

        // selected new option element 
        option.setAttribute("selected", "selected");


        try {
            textb.add(option, null); //Standard
        } catch(error) {
            textb.add(option); // IE only
        };

        /*
        *  I do not understand selected added option value "" ?? 
        */ 
        //textb.value = "";

       }());
};

hasValue関数:

function hasValue(element, value) {
    var results = true;

    for (var i=element.options.length-1; i >= 0; i--) (function() {

        if (element.options[i].value == value) (function() { 
            results = false;
        }());
    }());

    return (results);
};

落ち着いて..

于 2012-09-17T11:45:48.153 に答える
0

次のコードを追加するのではなく、値を削除していないので、問題は解決しました。

function addCombo() {
    var reportID = '<%=reportid%>';
    var options= document.getElementById('reportnames').options;
    for (var i= 0, n= options.length; i < n ; i++) {
        if (options[i].value==reportID) {
            document.getElementById("reportnames").selectedIndex = i;
            break;
        }
    }
}
于 2012-09-21T11:45:32.280 に答える