2011-02-23 76 views
0

我想添加选项到选择列表后擦除文本框的内容之后,下面是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

什么目前与该代码会发生什么? – justkt 2011-02-23 15:06:57

+0

没什么 - 它增加了新的选项,但没有清除该字段。 – firestruq 2011-02-23 15:12:12

+0

脚本似乎没问题。你有围绕控制的'

'吗?如果你这样做,可能在你看到'createOption()'的效果之前就已经提交了。 – Humberto 2011-02-23 15:13:35

回答

1

事件侦听器是它会调用函数内部,它造成的问题。

document.getElementById('add_option').onclick = createOption; 

把它放在外面createOption();

+0

我不好,谢谢。 – firestruq 2011-02-23 15:15:16

1

我这么练出来的定期JS,我只能为您生产出一个jQuery的例子。希望能帮助到你!

现场演示 http://jsfiddle.net/Jp27y/

$('#addButton').click(function(){ 
    createOption(); 
}); 

function createOption(){ 
    $('#theaterSelectControl').append($("<option></option>").text($('#theater_name').val()));  
    $('#theater_name').val(""); 
}