我希望根据用户从下拉框中选择的数字显示多个文本框。因此,如果用户选择1,则会出现1个框,然后会出现2个框等。
我的下拉 -
<select name="numNames" id="numNames">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
当用户选择我想要显示的数字时:
<div class="form-group">
<label for="Name" class="col-sm-4 control-label">Name:</label>
<div class="col-sm-8 input">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter name" required="required">
</div>
</div>
来自@Elise Chant的代码正在寻找,但是当我将它放在编辑器中时,它不起作用,但在她链接的示例中起作用。
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
var el = '<div class="form-group">' +
'<label for="Name" class="col-sm-4 control-label">Name:</label>' +
'<div class="col-sm-8 input">' +
'<input type="text" class="form-control" id="name" name="name" placeholder="Enter name" required="required">' +
'</div>' +
'</div>';
$('#numNames').on('change', function(e) {
var numSelected = $(this).val();
appendControls(numSelected);
});
function appendControls(num) {
$('#elcontainer').empty();
for (var i=0; i<Number(num); i++) {
$('#elcontainer').append(el);
}
}
</script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<select name="numNames" id="numNames">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id="elcontainer"></div>
</body>
</html>
任何人都知道为什么这不起作用?
答案 0 :(得分:1)
http://jsbin.com/zewadupivi/1/edit?js,output
var el = '<div class="form-group">' +
'<label for="Name" class="col-sm-4 control-label">Name:</label>' +
'<div class="col-sm-8 input">' +
'<input type="text" class="form-control" id="name" name="name" placeholder="Enter name" required="required">' +
'</div>' +
'</div>';
$('#numNames').on('change', function(e) {
var numSelected = Number($(this).val());
appendControls(numSelected);
});
function appendControls(num) {
$('#elcontainer').empty();
for (var i=0; i<num; i++) {
$('#elcontainer').append(el);
}
}
答案 1 :(得分:0)
$('select').on('change', function (e) {
var optSel = $("option:selected", this);
var valSel = Number(this.value);
for(var i = 0; i < valSel ; i++) {
$("body").append('<div class="form-group"><label for="Name" class="col-sm-4 control-label">Name:</label><div class="col-sm-8 input"><input type="text" class="form-control" id="name" name="name" placeholder="Enter name" required="required"></div></div>');
}
});