Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 747
Ashwin Kumar Avatar asked Mar 28 '13 10:03

Ashwin Kumar


2 Answers

<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';

    }
like image 42
sasi Avatar answered Oct 06 '22 00:10

sasi


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"/>');
    }
});
like image 168
Peter Rasmussen Avatar answered Oct 06 '22 00:10

Peter Rasmussen