我有一个表单,我需要这样的工具,用户在文本字段中输入一些数据并点击使用jquery进入该时间它应该创建新的控件,如新文本字段,下拉菜单,文本字段。它的作品也是如此,但它有一个错误,比如当用户输入另一个数据并且命中时输入之前控件的时间值,下拉列表和文本字段更改为其默认值。帮我解决一下
这是我的代码:
<script type="text/javascript">
function addMbo(value){
var div = document.getElementById('mboTable');
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
event.preventDefault();
var divName = document.getElementById('mboName');
var divState = document.getElementById('mboState');
var divProgress = document.getElementById('mboProgress');
divName.innerHTML = divName.innerHTML + "<input class=form-control type=text name=mboName value='" + value + "' id=mboNamw/>"
divState.innerHTML = divState.innerHTML + "<select class=form-control > <option value=1>In Progress </option><option <value=2>Completed</option><option value=3>Cancled</option></select>"
divProgress.innerHTML = divProgress.innerHTML + "<input class=form-control type=text name=progress id=progress />"
document.getElementById('mboNameInput').value = null;
}
}
</script>
HTML code:
<div class="col-sm-4">
<div class="row">
<div class="col-sm-5">
<b>Objectives</b>
</div>
<div class="col-sm-4">
<b>Status</b>
</div>
<div class="col-sm-3">
<b>Compl. %</b>
</div>
</div>
<div class="row">
<div id="mboTable">
<div id="mboName" class="col-sm-5"></div>
<div id="mboState" class="col-sm-4"></div>
<div id="mboProgress" class="col-sm-3"></div>
</div>
</div>
<div class="row" >
<div class="col-sm-5">
<input type="text" id="mboNameInput" class="form-control " onkeydown="addMbo(this.value)" placeholder="Your MBO...">
</div>
</div>
</div>
答案 0 :(得分:2)
检查以下解决方案将为您解决
$(function() {
$("#mboNameInput").on("keydown", function(e) {
if (e.keyCode == 13) {
var $nameDiv= $("#mboName");
var $stateDiv= $("#mboState");
var $progressDiv= $("#mboProgress");
$nameDiv.append($("<input/>").attr("type","text").attr("value",$(this).val()));
$stateDiv.append($("<select/>").append($("<option/>").text("InProgress")).append($("<option/>").text("Completed")).append($("<option/>").text("Canceled")));
$progressDiv.append($("<input/>").attr("type","text"));
$(this).val('');
}
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-bordered table-responsive">
<tr>
<th>Objectives</th>
<th>Status</th>
<th>% Comp</th>
</tr>
<tr>
<div id="mboTable">
<td><div id="mboName" class="col-lg-4"></div></td>
<td><div id="mboState" class="col-lg-5"></div></td>
<td><div id="mboProgress" class="col-lg-3"></div></td>
</div>
</tr>
<tr>
<td>
<div class="col-lg-5">
<input type="text" id="mboNameInput" class="form-control " placeholder="Your MBO..."></div>
</td></tr> </table>
&#13;