views:

170

answers:

1

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.

+1  A: 

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:" );
           $(this).append('<option value="'
                             + other
                             + '" selected="selected">'
                             + other
                             + '</option>');
        }
    });
});
tvanfosson
@tvanfosson the solution looks terrific but when I add it to my page nothing happens. If I understand it right (and I don't understand javascript or jquery well) it searches all the selects for either missing values or empty values ("") and will replace the value via prompt.
zmg
Sorry, I must have made a mistake. The function works great, thanks so much!
zmg
The way it works is when a select changes, it checks the new value. If it is empty, then it prompts (as in your previous solution) for a new value and constructs a selected option from the value and appends it to the select that was changed.
tvanfosson