Adding Option to Select box

Discussion in 'Javascript' started by shankwheat, Apr 27, 2007.

  1. shankwheat

    shankwheat Guest

    I'm trying to add an option to a select box dynamically. A typical
    string value is delimitted by a # character. There will always be
    only one option to add. What's happening is that the option text value
    shows up twice in the selectbox.


    I'm getting this:

    <select id="ddlSavedBenchmarks">
    <option>mytext</option>
    <option>28</option>
    </select>

    Instead of this:


    <select id="ddlSavedBenchmarks">
    <option value="28">mytext</option>
    </select>


    results = "mytext#28"

    // Split the delimited response into an array
    results = xmlHttp.responseText.split("#");

    for (var i=0; i < results.length;++i){
    addOption(document.choiceForm.ddlSavedBenchmarks, results,
    results);
    }


    function addOption(selectbox,text,value )
    {
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);
    }


    Thanks
     
    shankwheat, Apr 27, 2007
    #1
    1. Advertisements

  2. shankwheat

    RobG Guest



    Your example has different values for the option's text and value
    attributes, but this code should make them the same - which do you
    want? Anyhow, use something like:

    var sel = document.choiceForm.ddlSavedBenchmarks;
    sel.options[sel.options.length] = new Option(results,
    results);

    Using this method, IE will not properly add the text property, use:

    optn.appendChild(document.createTextNode(text));
     
    RobG, Apr 27, 2007
    #2
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.