0

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

6
  • 1
    Interesting. What have you tried so far? Where are you stuck? Jul 7, 2011 at 15:20
  • I don't think you'll be able to do this in Lynx or good 'ole "telnet to port 80"... or NCSA Mosaic or Netscape 1.x...
    – Marc B
    Jul 7, 2011 at 15:21
  • 1
    Why not use jQuery? I've never heard of NOT using jQuery as a requirement Jul 7, 2011 at 15:21
  • @Felix Kling: I tried: document.getElementById('myElement').type = 'select-one'; on <input type="hidden" name="myElement" id="myElement" value="some text" />
    – blez
    Jul 7, 2011 at 15:22
  • select-one is not even a valid value for type. Jul 7, 2011 at 15:24

3 Answers 3

1

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.

0

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.

2
  • OP wants to use Javascript, but not jQuery. Jul 7, 2011 at 15:22
  • He only said he does not want to use jQuery. Jul 7, 2011 at 15:22
0

You can use InnerHTML but it isn't compatible with all browsers (Not compatible with: NN4 , OP5, OP6)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.