I want to erase content of textfield after adding option into select list, here is the html code example:
<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>
here is js code:
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 = "";
}
what am I doing wrong?
thanks
Your event listener is inside the function it calls, it's causing problems.
document.getElementById('add_option').onclick = createOption;
Put it outside createOption();
I'm so out of practice with regular JS that I can only produce a jQuery example for you. Hope it helps!
LIVE Demo http://jsfiddle.net/Jp27y/
$('#addButton').click(function(){
createOption();
});
function createOption(){
$('#theaterSelectControl').append($("<option></option>").text($('#theater_name').val()));
$('#theater_name').val("");
}
精彩评论