Java Questions
Java Questions

Reputation: 7953

how to set values to combobox dynamically in javascript

this is how i set value to a combobox using dwr call,

var reportID = '<%=reportid%>'; var reportName = '<%=reportname%>'; loadReportNames(reportUserID);

function loadReportNames(reportUserID){
    CustomiseReportAction.getReportNames(reportUserID, addReportNamesDropDown);
}
function addReportNamesDropDown(resultMap){
    dwr.util.removeAllOptions("reportnames");
    dwr.util.addOptions("reportnames",resultMap);
}

after loading the combo box i set values to loaded combo like this,

document.getElementById("reportnames").value=reportID;

but the reportID is not set,

what could be the problem please help me to resolve this.

UPDATE :

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 = "";
}

used above method it gives me no exception but no results.

Regards

Upvotes: 3

Views: 50887

Answers (2)

Java Questions
Java Questions

Reputation: 7953

I have not removed the value rather i added the following code, it solved me the problem.

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

Upvotes: 5

Wutz
Wutz

Reputation: 2942

Edit: I just double checked and it should work like you did it, so disregard my original post. Are you sure the content of reportID exactly matches one of the options? If its a number, not a string, you might want to try

document.getElementById("reportnames").value = "" + reportID;


Original: To set the selected option of a combobox (assuming you mean html "select") you need to set the "selected" attribute of the desired option to true.

var select = document.getElementById("reportnames");
for (var i = 0; i < select.options.length; i++)
{
    if (...)
        select.options[i].selected = true;
}


You will need some way to identify the option, I'd do it by saving the reportID in it. Then you could replace the ... with:

select.options[i].ReportId == reportID


If you set the reportID as the "id"-attribute of each option you could even do it like this:

document.getElementById(reportID).selected = true;

Upvotes: 4

Related Questions