2

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" />
3
  • Would it need to change back with the new option added? Commented Jan 8, 2011 at 13:04
  • 2
    Bad user experience design, since the user cannot change his mind and select another option after the select box is replaced.. Better to just show/hide an additional input box when the custom is selected/deselected.. Commented Jan 8, 2011 at 13:16
  • Unless you switch it back with the new option (although I would be inclined to rather show the input box when custom is selected and hide it the rest of the time) - i.e. no change to visibility of the dropdown. Commented Jan 8, 2011 at 18:44

4 Answers 4

5

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

$('#foo').change(function() {
    if ($(this).val() === 'custom') {
        $(this).replaceWith('<input name="foo" type="text" />');
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

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)...

Comments

1

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();
      }
});

Comments

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

});

1 Comment

Wouldn't this only trigger when, while custom is selected, the user clicks the dropdown?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.