【问题标题】:How to dynamically turn a text field into dropdown?如何动态地将文本字段变成下拉列表?
【发布时间】:2011-07-07 23:32:35
【问题描述】:

名字说明了一切。我想使用 javascript 将文本字段元素更改为组合框。如果是跨浏览器就好了。

编辑:我可能会使用 jQuery

【问题讨论】:

  • 有趣。你试过什么了?你被困在哪里了?
  • 我认为您无法在 Lynx 或良好的 'ole "telnet to port 80"... 或 NCSA Mosaic 或 Netscape 1.x 中执行此操作...
  • 为什么不使用 jQuery?我从来没有听说过不使用 jQuery 作为要求
  • @Felix Kling:我试过了:document.getElementById('myElement').type = 'select-one';在
  • select-one 甚至不是type 的有效值。

标签: javascript dom cross-browser


【解决方案1】:

诀窍是创建下拉元素并将其添加到表单中,以及删除文本字段。你可以有这样的 HTML:

<form id='myform'>
    ...
    <span id='textelement'>text goes here</span>
    <input type='button' value='change text to dropdown' onclick='change()'/>
    ...
</form>

那么你的change() 函数可能是这样的:

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);
    ...
}

请注意,我尚未测试此代码 - 仅将其用作起点。

【讨论】:

    【解决方案2】:

    您要更改它是客户端还是服务器端。如果客户端真的没有办法不使用某种javascript。

    【讨论】:

    • OP 想使用 Javascript,而不是 jQuery。
    • 他只说不想用jQuery。
    【解决方案3】:

    您可以使用 InnerHTML,但它不兼容所有浏览器(不兼容:NN4、OP5、OP6)

    【讨论】:

      猜你喜欢
      • 2016-10-19
      • 2011-03-17
      • 1970-01-01
      • 2021-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-04
      • 1970-01-01
      相关资源
      最近更新 更多