[英]Populate Drop Down List using jquery from textbox
我有一个其ID为其他ID的文本框,我想将此文本框值填充到下拉列表中。这是我用来填充的javascript ...但这不起作用。任何建议将不胜感激...! 我想这样做: -http : //viralpatel.net/blogs/demo/dynamic-combobox-listbox-dropdown-in-javascript.html
<SCRIPT language="javascript">
function addCombo() {
var textb = $('#other').attr('id');
var combo = $('#category').attr('id');
alert(combo);
var option = document.createElement("option");
option.text = $('#other').val();
alert(option.text);
option.value = $('#other').val();
try {
combo.add(option, null); //Standard
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}
</SCRIPT>
这是下拉列表的代码
<td>Category</td>
<td><select class="size" id="category" name="category" width="30px">
<option width="30px" value="" selected="selected" >Select</option>
<option value="food">Food</option>
<option value="rent">Rent</option>
<option value="gas">Gas</option>
<option value="enter">Entertainment</option>
<option value="grocery">Grocery</option>
<option value="general">General</option>
<option value="other">Other</option></select></td>
</tr>
<tr>
<td>Other</td>
<td><input type="text" id="other" name="other"/></td>
<td><input type="button" data-role="button" value="Add" onclick="addCombo()"></td>
</tr>
我相信这是因为
var textb = $('#other').attr('id');
var combo = $('#category').attr('id');
您不是将这些元素的ID分配给变量而不是元素吗?
我的意思是……执行此代码后,textb确实是输入元素,还是仅仅是字符串“ other”?
尝试这个:
var textb = $('#other');
var combo = $('#category');
编辑:
function addCombo() {
var textb = document.getElementById("other");
var combo = document.getElementById("category");
var option = document.createElement("option");
option.text = textb.value;
option.value = textb.value;
try {
combo.add(option, null); //Standard
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}
由于您已经在使用jQuery:
function addCombo() {
var optName = $("#other").attr("value");
$('#category').append("<option value='"+ optName + "'>" + optName + "</option>");
$("#other").attr("value", "");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.