faqts : Computers : Programming : Languages : JavaScript : Forms : SELECT

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

10 of 23 people (43%) answered Yes
Recently 5 of 10 people (50%) answered Yes

Entry

How can I dynamically add an option to a select list from a separate text box

Feb 3rd, 2005 04:36
jsWalter, Cathy Bappe,


Try this... 
This is a small subset of a larger SELECT Object functiosn and methods 
collection I've been piecing together for years. 
Walter 
============================================ 
<table border='1'> 
    <tr> 
        <td> 
            Add Item:<br> 
            <input type="text" name="itemText" id="itemText" 
value="text" size="13"> 
            <br> 
            Value:<br> 
            <input type="text" name="itemValue" id="itemValue" 
value="value" size="13"> 
        </td> 
<!-- Add button --> 
        <td align="center" valign="middle"> 
            <button onClick="addOption ( 'leftBox', 
                             document.getElementById('itemText').value, 
document.getElementById('itemValue').value, 
                             false, 
                             true, 
document.getElementById('overwrite').checked ) 
                            ">Add Item</button> 
            <br /> 
            <input type="checkbox" name="overwrite" id="overwrite" /> 
Overwrite 
        </td> 
    </tr> 
</table> 
            <select name="leftBox" 
                    id="leftBox" 
                    size="4" 
                    class="myList"> 
                <option value="4">Item 4</option> 
                <option value="1">Item 1</option> 
                <option value="3">Item 3</option> 
                <option value="2">Item 2</option> 
            </select> 
<script language="JavaScript" 
        type="text/javascript"> 
// {{{ addOption() 
   /** 
    * Method public void addOption( object, string, [boolean[, 
boolean[, boolean ]]] ) 
    * 
    * Add Option Item to Select Object, but only if the Option Item 
    * Value does not already exist, regardless of Display Text 
    * 
    * @name addOptionUniqueByValue 
    * @author Martin Webb <martin@irt.org> and Michel Plungjan 
<michel@irt.org> 
    * @copyright 1996-2001 irt.org, All Rights Reserved. 
    * @original http://developer.irt.org/script/916.htm 
    * 
    * @category SELECT Object Extentions 
    * 
    * @access public 
    * @since v1.0 
    * 
    * @param mixed  $objSelect Required Object Reference or ID name to 
Select Form Object 
    * @param string $strText   Required Select Item Display Text 
    * @param string $strValue Select Item Option Value 
    * @param boolean $bolDefaultSelected  If this item is to be the 
Default Selected Item 
    * @param boolean $bolSelected         If this item is to be 
currenly Selected Item 
    * @param boolean $bolOverWrite        If this item should be 
"overwritten" or not 
    */ 
    function addOption($objSelect, $strText, $strValue, 
$bolDefaultSelected, $bolSelected, $bolOverWrite) 
    { 
        // Default value of found Item 
        $foundIndex = new Boolean ( false ); 
        // If $objSelect is a string, convert to Object Reference 
        // Then see if Object Reference exists 
        if ( ( typeof ( $objSelect ) ) == 'string' ) 
            $objSelect = document.getElementById($objSelect); 
        // If we have nothing to deal with, just bale... 
        if ( ( ! $objSelect ) ||  ( ! $strText ) ) 
            return $foundIndex; 
        // If a Value was not sent, set it from Text 
        if ( ( $strValue == '' ) || ( $strValue == null ) ) 
            $strValue = $strText; 
        // See if this exists or not 
        $foundTextIndex  = findOptionByText($objSelect, $strText) 
        $foundValueIndex = findOptionByValue($objSelect, $strValue) 
        // See if this new addition was found 
        // And if it was found in both Text AND Value 
        if ( ( typeof ( $foundTextIndex ) == 'number' ) && ( typeof 
( $foundValueIndex ) == 'number' ) ) 
        { 
            // If the Index for Text and Value are the same, great... 
            if ( $foundTextIndex == $foundValueIndex ) 
            { 
                // Keep index 
                $foundIndex = $foundValueIndex; 
            }   // if same 
            // Opps! indices don't match! Can't have that! 
            else 
            { 
                alert ( 'Sorry, but the "Text" and the "Value" for this 
item exists in seperate Items.' 
                         + "\n" + 
                         'Please correct this problem.' ); 
            } 
        }   // if both Numbers 
        // Was it found in Text OR Value 
        else if ( ( typeof ( $foundTextIndex ) == 'number' ) || 
( typeof ( $foundValueIndex ) == 'number' ) ) 
        { 
            // Keep index 
            $foundIndex = ( $foundTextIndex != false ) ? 
$foundTextIndex : $foundValueIndex; 
        } 
        // OK, we have something, so porcess it, maybe! ;) 
        if ( $foundIndex != false ) 
        { 
            // See if we are to overwrite the found duplicate 
            if ( $bolOverWrite == true ) 
            { 
                // Since it is to be overwritten, we need to kill the 
orginal first 
                deleteOption($objSelect, $foundIndex); 
                // The Item was removed, so clear the flag 
                $foundIndex = new Boolean ( false ); 
            }   // if $bolOverWrite 
            else 
            { 
                $errMsg  = 'Sorry, but the '; 
                $errMsg += ( $foundValueIndex == true ) ? 'Text ' : 
'Value '; 
                $errMsg += 'of this new item already exists.'; 
                alert ( $errMsg ); 
            }   // else -  if $bolOverWrite 
        } 
        // a FALSE $foundIndex means he new Item can be Added to SELECT 
List 
        if ( $foundIndex == false ) 
        { 
            // Use built-in Option Object Creation method 
            var $objOption = new Option($strText, $strValue, 
$bolDefaultSelected, $bolSelected); 
            // Insert new Option Object into Select Object 
            $objSelect.options[$objSelect.length] = $objOption; 
            // Set return value 
            $itemAdded = new Boolean ( true ); 
        } 
        // We can't the item 
        else 
        { 
            // Set return value 
            $itemAdded = new Boolean ( false ); 
        } 
    }; 
// }}} 
// {{{ findOptionByValue() 
   /** 
    * Method public void findOptionByValue( object, string ) 
    * 
    * Find an Option Item of a Select Object by its OPTION Value, 
    * or if OPTION does not have a value, its Display Text 
    * 
    * @name findOptionByValue 
    * @author Walter Torres <jsWalter@torres.ws> 
    * 
    * @category SELECT Object Extentions 
    * @uses findOption() 
    * 
    * @access public 
    * @since v1.3 
    * 
    * @param mixed  Reference to Select Form Object, or its ID name 
    * @param string Select OPTION Value to search for 
    * @return mixed integer of OPTION index, or Boolean FALSE if not 
found 
    * 
    */ 
    function findOptionByValue($objSelect, $strValue) 
    { 
        // Straight pass-through 
        return findOption($objSelect, $strValue, 'value' ); 
    }; 
// }}} 
// {{{ findOptionByText() 
   /** 
    * Method public void findOptionByText( object, string ) 
    * 
    * Find an Option Item of a Select Object by its Display Text 
    * 
    * @name findOptionByText 
    * @author Walter Torres <jsWalter@torres.ws> 
    * 
    * @category SELECT Object Extentions 
    * @uses findOption() 
    * 
    * @access public 
    * @since v1.3 
    * 
    * @param mixed  Reference to Select Form Object, or its ID name 
    * @param string Select OPTION Display Text to search for 
    * @return mixed integer of OPTION index, or Boolean FALSE if not 
found 
    * 
    */ 
    function findOptionByText($objSelect, $strText) 
    { 
        // Straight pass-through 
        return findOption($objSelect, $strText, 'text' ); 
    }; 
// }}} 
// {{{ findOption() 
   /** 
    * Method public void findOptionB( object, string ) 
    * 
    * Find an Option Item of a Select Object by its Display Text 
    * or OPTION value 
    * 
    * @name findOption 
    * @author Walter Torres <jsWalter@torres.ws> 
    * 
    * @category SELECT Object Extentions 
    * @uses none 
    * 
    * @access public 
    * @since v1.3 
    * 
    * @param mixed  Reference to Select Form Object, or its ID name 
    * @param string What to look for 
    * @param string Where to look for it, 'text' or 'value' 
    * @return mixed integer of OPTION index, or Boolean FALSE if not 
found 
    * 
    */ 
    function findOption($objSelect, $strNeedle, $strSearch) 
    { 
       /** 
        * Default return value 
        * 
        * Returns the index of a found OPTION Item or boolean upon 
failure 
        * Default value is set at FALSE 
        * 
        * @var mixed $_found index of a found OPTION Item or not 
        * @access private 
        * @static 
        */ 
        var $_found = new Boolean( false ); 
        // If $objSelect is a nothing [''], convert to a NULL 
        if ( $objSelect == '' ) 
            $objSelect = null; 
        // If $objSelect is a string, convert to Object Reference 
        // Then see if Object Reference exists 
        else if ( ( typeof ( $objSelect ) ) == 'string' ) 
            $objSelect = document.getElementById($objSelect); 
        // If we have nothing to deal with, just bale... 
        if ( ( $objSelect ) && ( $strNeedle ) && 
             ( ( $strSearch == 'text' ) || ( $strSearch == 
'value' ) ) ) 
        { 
            for (var $i = 0; $i < $objSelect.options.length; $i++) 
            { 
                if ( $strSearch == 'value' ) 
                    $objHayStack = $objSelect[$i].value; 
                else if ( $strSearch == 'text' ) 
                    $objHayStack = $objSelect[$i].text; 
                if ( $objHayStack == $strNeedle ) 
                { 
                    $_found = parseInt ( $i ); // We found a match 
                    break; 
                } 
            } 
        } 
        // Send back what we have 
        return $_found; 
    }; 
// }}} 
// {{{ deleteOption() 
   /** 
    * Method public void deleteOption( object, int ) 
    * 
    * Delete given Item Index from given Select Object 
    * 
    * @name deleteOption 
    * @author Martin Webb <martin@irt.org> and Michel Plungjan 
<michel@irt.org> 
    * @copyright 1996-2001 irt.org, All Rights Reserved. 
    * @original http://developer.irt.org/script/916.htm 
    * 
    * @category SELECT Object Extentions 
    * 
    * @access public 
    * @since v1.0 
    * 
    * @param ref object Reference to Select Form Object 
    * @param int index Index of which Item to remove 
    * 
    */ 
    function deleteOption($objSelect, $intIndex) 
    { 
        // If $objSelect is a string, convert to Object Reference 
        // Then see if Object Reference exists 
        if ( ( typeof ( $objSelect ) ) == 'string' ) 
            $objSelect = document.getElementById($objSelect); 
        // If we have nothing to deal with, just bale... 
        if ( ( ! $objSelect ) ||               // Some browsers will 
define this 
             ( $objSelect == 'undefined' ) ||  // othes give this 
             ( $objSelect == '' ) ||           // Konqueror gives this 
             ( ! $intIndex ) )                 // Without an index, we 
have nothing to do 
            return; 
        $objSelect.options[$intIndex] = null; 
    }; 
</script>