2016-08-02 51 views
0

最初我有一个文本框/选择框,当用户输入的东西或选择的东西生成另一个文本框/选择框,我也可以设置限制多少文本框/选择框可以生成。当用户输入东西时动态生成文本框

请指点我如何才能做到这一点

+1

使用'.append()' – guradio

+0

确定,我怎么可以检查用户输入的任何东西,或不? –

回答

2

您可以使用jQuery append()方法动态创建HTML。

$("#ddlOptions").on("change", function(e) { 
 

 
    var len = $('.txtInput').length; 
 
    if (len == 0) { 
 
    $('.container').append('<br> <input type="text" id=txtTextBox_' + len + ' class="txtInput" /> <br>'); 
 
    } 
 
}); 
 

 
$(document).on("change", '.txtInput', function() { 
 
    var len = $('.txtInput').length; 
 
    
 
    if ($(this).val() != "") { 
 
    $('.container').append('<br> <input type="text" id=txtTextBox_' + len + ' class="txtInput" /> <br>'); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="container"> 
 
    <select id="ddlOptions"> 
 
    <option>option 1</option> 
 
    <option>option 2</option> 
 
    <option>option 3</option> 
 
    <option>option 4</option> 
 
    </select> 
 
</div>

+0

我想添加一个如果第一个文本框填充生成另一个如果填充生成另一个等.. –

+0

@ websmentor.com请检查片段。代码更新并让我知道你是否面临任何问题。 :) –

+0

谢谢你的工作正常.. –

0

var counter=0; 
 
function generate(){ 
 
    var newTxt='<input type="text">'; 
 
    var newSel='<select><option value="">--select--</option></select>'; 
 
    var txtlimit=document.getElementById('txtlimit'); 
 
    var div=document.getElementById('newCtrls'); 
 
    var totalElem=div.getElementsByTagName('input').length; 
 
    
 
    if(!isNaN(txtlimit.value) && txtlimit.value!=''){ 
 
    if(parseInt(txtlimit.value)>counter && 
 
     parseInt(txtlimit.value)>totalElem){ 
 
     div.innerHTML += newTxt + newSel+'<br>'; 
 
     counter++; 
 
    } 
 
    }else{ 
 
    div.innerHTML +=newTxt + newSel+'<br>'; 
 
    } 
 
}
<input type="text" id="txtlimit" placeholder="Enter Limit"><br> 
 
<input type="text" onkeyup="generate();"> 
 
<select onchange="generate();"> 
 
    <option value="Item1">--select--</option> 
 
    <option value="Item1">Item1</option> 
 
    <option value="Item2">Item2</option> 
 
    <option value="Item3">Item3</option> 
 
</select><br> 
 
<div id="newCtrls"> 
 
    <h3>Dynamic Controls Here</h3> 
 
</div>