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.

Answers


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.


Need Your Help

Passing arguments to ruby interpreter when stdin is used as ruby source

ruby ssh wget

I built a rails deploy dashboard that kicks off a ruby script on a remote machine to update a deployed application.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.