Wednesday, March 30, 2011

Numeric Dropdown that 'turns into' a textbox when I select 'More'

I need to make a dropdown that has the numbers 0 through 10 in it, plus a "--More--" option at the bottom. If the user selects '--More--' then I want the dropdown to 'turn into' a textbox so they can enter a numeric value.

I want the field name posted back to have the same form value regardless of which entry method was used. Preferably I want it to degrade if the user doesn't have javascript - either by not showing the 'More' option or just using a textbox.

I'm using ASP.NET MVC - in other words the solution I'm looking for doesn't need to work with some special server side technology. Although I am already using jQuery.

From stackoverflow
  • Try this:

    HTML:

    <input class="numberEntry" name="howMany" type="text" />
    

    jQuery:

    $(document).ready(function() {
    
        // get the name from the existing text entry input
        var numberEntryName = $(".numberEntry").attr("name");
    
        // create some new HTML to replace our input with
        var numberSelector = '';
    
        // make the select box
        numberSelector += '<select name="' + numberEntryName + '">';
        for (var i = 0; i <= 10; i++)
        {
            numberSelector += '<option value="' + i + '">' + i + '</option>';
        }
        // add the more link
        numberSelector += '<option value="MORE">- More -</option>';
    
        numberSelector += '</select>';
    
        // now grab the existing input field so we can display it later when
        // the user clicks on the more link
        var numberEntryHtml = $(".numberEntry").wrap("<div>").html();
    
        // replace the existing input field with our new HTML
        $(".numberEntry").replaceWith(numberSelector);
    
        // add a click event to the more link so that we'll show our
        // old text input field when "more" is clicked
        $("select[name=" + numberEntryName + "]").bind("change", function(e) {
            if ($(this).val() == "MORE")
                $(this).replaceWith(numberEntryHtml);
        });
    
    
    });
    

    This code is untested, but it should give you an idea of the design pattern.

    bendewey : This is great, but the user wants an option tag with ----More----
    bigmattyh : updated... still untested though.

0 comments:

Post a Comment