Ashwin Kumar
Ashwin Kumar

Reputation: 101

dropdown option and action

I have a drop down and inside that i have options. On clicking the option it must display fields respectively. Like for option1 == one text box option2 == two text box and so on...

<select id="dropdown">

    <option value="A">option1</option>
    <option value="B">option2</option>
    <option value="C">option3</option>
    <option value="D">option4</option>
</select>

on clicking option1 one field must be shown. on option2 two fields.. am new to javascript and html. Please help friends..

Upvotes: 6

Views: 16196

Answers (2)

Peter Rasmussen
Peter Rasmussen

Reputation: 16922

If you can use jquery it can be done like below. On change select a data attribute containing the number of textboxes to display. Then for loop through them and append.

Demo

Html:

<select id="dropdown">
    <option value="A" data-number="1">option1</option>
    <option value="B" data-number="2">option2</option>
    <option value="C" data-number="3">option3</option>
    <option value="D" data-number="4">option4</option>
</select>
<div id="textBoxContainer">

</div>

Javascript:

$('#dropdown').change(function(){
    $('#textBoxContainer').empty();
    var number = $(this).find('option:selected').attr('data-number');
    for (var i = 0; i < number; i++){
          $('#textBoxContainer').append('<input type="text"/>');
    }
});

Upvotes: 6

sasi
sasi

Reputation: 4318

<select id="dropdown" onChange="showHide()">

    <option value="A">option1</option>
    <option value="B">option2</option>
    <option value="C">option3</option>
    <option value="D">option4</option>
</select>


 function showHide()
 {
   hideAll();
  var val = document.getElementById("dropdown").value;

  if(val == "A")
   document.getElementById("firstTextBoxId").style.display = 'block';
  else if(val == "B")
   document.getElementById("secondTextBoxId").style.display = 'block';
  else if(val == "C")
   document.getElementById("ThirdTextBoxId").style.display = 'block';
  else if(val == "D")
   document.getElementById("FourthTextBoxId").style.display = 'block';

}


function hideAll()
   {
      document.getElementById("firstTextBoxId").style.display = 'none';
      document.getElementById("secondTextBoxId").style.display = 'none';
      document.getElementById("thirdTextBoxId").style.display = 'none';
      document.getElementById("fourthTextBoxId").style.display = 'none';

    }

Upvotes: 2

Related Questions