I have a textbox whose id is other and I want to populate this textbox value into drop down list This is javascript I am using to populate... but this is not working.. Any suggestion will be appreciated...!! I want to do like this:- 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(optio开发者_Python百科n.text);
option.value = $('#other').val();
try {
combo.add(option, null); //Standard
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}
</SCRIPT>
This is the code of drop down list
<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>
I believe its because
var textb = $('#other').attr('id');
var combo = $('#category').attr('id');
Aren't you assigning id's of these elements to variables, instead of elements?
I mean... is textb really a input element after this code executes, or is it just a string "other"?
Try this:
var textb = $('#other');
var combo = $('#category');
Edit:
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 = "";
}
Since you're already using jQuery:
function addCombo() {
var optName = $("#other").attr("value");
$('#category').append("<option value='"+ optName + "'>" + optName + "</option>");
$("#other").attr("value", "");
}
精彩评论