我想在选项列表中添加选项后删除textfield的内容,这里是html代码示例:
<select size="15" style="width:230px" style="text-align:right" id="theaterSelectControl">
<option>111</option>
<option>222</option>
<option>333</option>
</select>
<p>
</p>
<form>
<input type="text" name="theater_name" value="" id="theater_name" style="width:225px">
</form>
</td>
</tr>
<tr>
<td align="right">
<input type="button" onclick="createOption()" value="add"> <!-- add to list button -->
</td>
</tr>
这里是js代码:
function createOption()
{
var theaterSelectControl = document.getElementById('theaterSelectControl');
var currentText = document.getElementById('theater_name').value;
var objOption = document.createElement("option");
objOption.text = currentText ;
objOption.value = currentText ;
theaterSelectControl.options.add(objOption);
document.getElementById('add_option').onclick = createOption;
resetField();
}
function resetField()
{
document.getElementById('theater_name').value = "";
}
我做错了什么?
感谢
答案 0 :(得分:1)
你的事件监听器在它调用的函数内部,这会导致问题。
document.getElementById('add_option').onclick = createOption;
将其放在createOption();
答案 1 :(得分:1)
我经常使用常规JS,我只能为你生成一个jQuery示例。希望它有所帮助!
现场演示 http://jsfiddle.net/Jp27y/
$('#addButton').click(function(){
createOption();
});
function createOption(){
$('#theaterSelectControl').append($("<option></option>").text($('#theater_name').val()));
$('#theater_name').val("");
}