Replace Listmenu with Textfield

Posted by BRADINO on Bradino See other posts from Bradino or by BRADINO
Published on Thu, 19 Feb 2009 00:36:48 +0000 Indexed on 2010/03/23 5:22 UTC
Read the original article Hit count: 646

Filed under:

Say you have a dropdown form field where you ask the user how they heard about you. You have numerous options and also an other field where if they selected other, then they enter the value in a text field. This is a cleaner alternative where if the user selects Other, then the dropdown turns into a textfield of the same name, so that your post routine, grooming, validation, writing to DB etc all works seamlessly. This example uses prototype JS library.

Here is a working example:

How did you hear about BRADINO?

All you have to do is have an dropdown option for Other and then add call the function onchange:

onchange="overrideListmenu('how-heard');"

Here is the javascript function that uses Prototype:

function overrideListmenu(field){
   
    if ($F(field) == 'Other'){
   
        Element.replace($(field), '<input name="'+field+'" id="'+field+'" type="text" value="">');
       
        $(field).focus();
   
    }

}

Here is the javascript function that uses jQuery:

function overrideListmenu(field){
   
    if ($('#'+field).val() == 'Other'){
   
        $('#'+field).after('<input name="'+field+'" id="'+field+'" type="text" value="">').remove();
       
        $('#'+field).focus();
   
    }

}

© Bradino or respective owner

Related posts about JavaScript