views:

333

answers:

1

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.

+1  A: 

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.

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