randomguy
randomguy

Reputation: 12242

Dropdown list to a text field with jQuery?

I would like to have a dropdown list with options A, B, C and Custom. When custom is selected, the dropdown would be replaced by a text field so that the user can provide a custom name, if he wishes so.

So, first we have something like this

<select id="foo" name="foo">
  <option value="a">A</option>
  <option value="b">B</option>
  <option value="c">C</option>
  <option value="custom">Custom</option>
</select>

And after custom is selected, the whole dropdown list would transform to this:

<input name="foo" type="text" />

Upvotes: 2

Views: 10226

Answers (4)

Leslie
Leslie

Reputation: 61

Here is a way to do it without hiding the select box, for better user experience according to @Gaby above.

It shows a text box when 'custom' option is selected and hides it when anything else is selected.

    $('#foo').change(function()
    {
      var $this = $(this),
      id = $this.attr('id'),
      $txt = $('input:text[name=' + id + ']');
      if ( $this.val() == 'custom')
      {
         if ($txt.length == 0)
         {
            $txt = $('<input type="text" name="'+ id +'" />');
            $this.after($txt);
          }
          $txt.show().focus();
      }
      else
      {
          $txt.hide();
      }
});

Upvotes: 1

Baz1nga
Baz1nga

Reputation: 15579

$('#foo').click(
function()
{
if($(this).val()==="custom")
{
//either toggle the select and input button
//or add markup here. and clear the old amrkup
}

});

Upvotes: 0

jcuenod
jcuenod

Reputation: 58375

How about this:

$('select.foo').bind('change', function(event) { 
 if ($(this).val() == "Custom")
 {
  $(this).hide()
  $("input.foo").show()
 }
});

you could bind the lost focus event of the input box to redisplay the dropdown and add it as an option if you want (just give the custom option an id and then change its text)...

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

Here's a demo using the .replaceWith() function:

$('#foo').change(function() {
    if ($(this).val() === 'custom') {
        $(this).replaceWith('<input name="foo" type="text" />');
    }
});

Upvotes: 5

Related Questions