Jquery dynamically update "other" option in select

javascript, jquery, select

Solution

This will get you started. This will add the functionality to any select on the page, appending a new value to the select (and leaving other still available in case a mistake has been made).

$(function() {
    $('select').change( function() {
        var value = $(this).val();
        if (!value || value == '') {
           var other = prompt( "Please indicate other value:" );
           if (!other) return false;
           $(this).append('<option value="'
                             + other
                             + '" selected="selected">'
                             + other
                             + '</option>');
        }
    });
});

Problem

I'm working on a project that will be using a lot of select menus to enter various data. I'd like to include an 'other' option directly in the select that will trigger a simple dialog and allow users to enter a custom value (where appropriate) similar to the following javascript code: ``` <script type="text/javascript" language="javascript"> function chkother(fld,len,idx) { if ((idx+1)==len) { other=prompt("Please indicate 'other' value:"); fld.options[idx].value=other; fld.options[idx].text=other; } } </script> ``` which works with a select: ``` <select onchange="chkother(this,this.options.length,this.options.selectedIndex)" name="example" id="example" class="formSelect"> <option value=""></option> <option value="yes">yes</option> <option value="no">no</option> <option value="other">other</option> </select> ``` And brings up a prompt that will update the option with the users text. I'd like to do something similar using jquery so I can look at extending the functionality and learning a bit of jquery, but I'm having trouble getting started.

Original source