javascript - 如何将下拉列表更改为 jQuery 中选择的文本框?

标签 javascript jquery drop-down-menu textbox

我有一个下拉列表,当我选择 Other 选项时,我希望它变成一个空文本框。

Enter image description here

HTML代码:

<select id='visit'>
    <option value='1' class='volunteer'>Romania</option>
    <option value='2' class='volunteer1'>Slovakia</option>
    <option value='3' class='volunteer2'>Belgium</option>
    <option value='4' class='volunteer3'>Other</option>
</select>

这是开始的最小 JavaScript 代码:

$('#visit').live('change', function () {
    if ((this.value) == 4) {
        alert("Other selected")
        //Code to change select list into textbox here
    }
});

JSFiddle where it can be tried is here .

我如何使用 jQuery 做到这一点?

最佳答案

尝试使用.replaceWith()在这种情况下,

$(this).replaceWith('<input/>');

DEMO

完整代码是,

$('#visit').live('change', function () {
    if ((this.value) == 4) {
      $(this).replaceWith($('<input/>',{'type':'text','value':'other'}));  
    }
});

DEMO


正如大家所说,替换 select 元素似乎是个坏主意, 因此,请尝试根据用户的选择显示/隐藏输入元素。

尝试,

$("input[type=text]").hide();
$('#visit').live('change', function () {  
    $(this).next('input[type=text]').toggle((this.value) == 4)
});

DEMO

关于javascript - 如何将下拉列表更改为 jQuery 中选择的文本框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24134942/

相关文章:

javascript - 更改链接颜色在 IE 中不起作用

javascript - 输入宽度适合内容

javascript - 谷歌地图和 Markermanager 抛出错误

javascript - 如果我从选定的选项中获取数组的名称,如何访问数组?

javascript - 尝试通过 ipc 将数据从一个 Electron 窗口发送到另一个 Electron 窗口

javascript - function(i,x) { x(); 是否有任何 JavaScript/Underscore/jQuery 快捷方式? }?

python - Python 中的可编辑组合框

asp.net-mvc - 填充 ASP.NET MVC DropDownList

javascript - 为什么这段代码不能正确显示输出?

jquery - 使用 jQuery 切换 Animate.css 类