Question

I have a select field in a form that allows you to select multiple options.

I need to create a new input textbox for every number of options selected, automatically.

For example, if you select on option in the select box, one input will appear below it. If you select 5, 5 inputs will appear below it.

I'm not sure if this can be done in just straight Javascript, or if I'll need to use jQuery or some other form of AJAX to get this done, but I'm not really sure how to approach this (I'm relatively new to using AJAX)

Was it helpful?

Solution

Well, jQuery was made just for this type of thing - i recommend using it to save yourself headaches.

My take on it.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<script type="text/javascript">

$(function()
{
  $('#test')
    .after( '<div id="option-inputs"></div>' )
    .find( 'option' ).each( function()
    {
      var $option = $(this);
      $option
        .data( '$input', $( '<span>' + $option.text() + ': </span><input><br>').appendTo( '#option-inputs' ).hide() )
        .bind( 'toggle-input', function()
        {
          var $input  = $option.data( '$input' );
          if ( $option[0].selected )
          {
            $input.show();
          } else {
            $input.hide();
          }      
        })
        .bind( 'click', function()
        {
          $(this).siblings().andSelf().trigger( 'toggle-input' );
        })
        .trigger( 'toggle-input' )
      ;
    })
  ;
});


</script>

</head>
<body>

<select id="test" multiple="multiple">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

</body>
</html>

OTHER TIPS

Just some quick thoughts.. Add a DIV under the Select Element.

using jQuery (or javascript) you can add a textbox for each select item add a textbox to the div. Something like:

var textboxString;
$("#SelectElement option:selected").each(function () {
                textboxString += "<input type='textbox' /><br>" // Add to this string as needed (Labels, css class, etx).
              });
$("#divElement").html(textboxString)

With html like this:

<select id="number_of_inputs"> 
  <option>1</option> 
  <option>2</option> 
  <option>3</option> 
  <option>3</option> 
  <option>5</option> 
</select> 

<div id="inputs"></div> 

You can use this jQuery:

$("#number_of_inputs").change(function() {
  var num = parseInt($(this).val());

  $("#inputs").html("");
  for(var i = 0; i < num; i++) {
    $("#inputs").append("<input type='text' /><br />");
  }
});

I actually like gw's JS better but here's another way to do it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top