How to dynamically turn a text field into dropdown?
The name says all. I want to change a text field element into combo box using javascript. It will be nice if it's cross-browser.
开发者_如何学运维EDIT: I may use jQuery
The trick is to create the dropdown element and add it to the form, as well as remove the text field. You can have HTML like this:
<form id='myform'>
...
<span id='textelement'>text goes here</span>
<input type='button' value='change text to dropdown' onclick='change()'/>
...
</form>
Then your change()
function could be something like this:
function change() {
var _form = document.getElementById('myform');
var _text = document.getElementById('textelement');
_form.removeChild(_text);
var _combo = document.createElement('select');
_combo.setAttribute('size', '1');
_combo.setAttribute('id', 'dropdownelement');
_form.appendChild(_combo);
_combo = document.getElementById('dropdownelement');
//add first value to the dropdown
var _opt = document.createElement('option');
_opt.text = 'New option 1';
_opt.value = '1';
_combo.add(_opt);
//add second value to the dropdown
_opt = document.createElement('option');
_opt.text = 'New option 2';
_opt.value = '2';
_combo.add(_opt);
...
}
Note that I haven't tested this code - use it as a starting point only.
Are you wanting to change it client side or server side. If client side there really is not way without using javascript of some sort.
You can use InnerHTML but it isn't compatible with all browsers (Not compatible with: NN4 , OP5, OP6)
精彩评论