Rahul Singh
Rahul Singh

Reputation: 1632

textboxes on dropsown select

I am beginner with jQuery. I want to use drop down in my page. Depending upon the selection of drop down value, no of text boxes should appear in page. Suppose I selected 8 than 8 text boxes appear and if then I select 4 than rest four should be removed. Please give me idea how to do it using jQuery.

Upvotes: 1

Views: 65

Answers (3)

Pranav
Pranav

Reputation: 8871

<html>
  <head>  
<title>Dynamic Form</title>  
 <script language="javascript">    
function changeIt()  
 {  
 document.getElementById("my_div").innerHTML="";  
var num=document.getElementById("select").options[document.getElementById("select").selectedIndex].value;  
 for(i=0;i<num;i++)  
{  
my_div.innerHTML = my_div.innerHTML +"<br><input type='text' name='mytext'+ i>"
}

}  
</script>

</head>
<body>

<form name="form" action="post" method="">
<select name="select" id="select">
    <option value="0">0</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    <option value="9">9</option>
    <option value="10">10</option>  
</select>  

<input type="button" value="test" onclick="changeIt()">
<div id="my_div"></div>
</form>
</body>
</html>

Upvotes: 0

Kumar
Kumar

Reputation: 5147

Rahul you are asking for an idea so here it is. Using jQuery you can find the value of a drop down or select element and use that value to simply append new text boxes. I would suggest not to create elements but insert html for those elements.

  <script src="http://code.jquery.com/jquery-latest.js"></script>

<select name="select" id="select">
    <option value="0">0</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    <option value="9">9</option>
    <option value="10">10</option>
</select>

<div id="textbox-container"></div>
<script>

$(document).ready(function() {
    $('#select').change(function() {
        var num = $('#select').val();
        $('.textboxes').remove();
        var textBoxesStr = '';
        for (i = 0; i < num; i++) {
            textBoxesStr = textBoxesStr + "<input type='text' class='textboxes' />";
        }
        $("#textbox-container").append(textBoxesStr);
    });
});
</script>

Code given above works for me.

Upvotes: 1

sushil bharwani
sushil bharwani

Reputation: 30187



jQuery('#select').change(function() {
var num = jQuery(this).val();

jQuery('.textboxes').remove();

for(i=0;i<num;i++)
{
jQuery("<input type='text' class='textboxes' />").appendTo("body");

}
});


Here select is the id of the selectbox.

Upvotes: 2

Related Questions