javascript 使用选项中的按钮创建选择输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21197954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:20:37  来源:igfitidea点击:

Create select input with button in options

javascriptjqueryhtml

提问by arielcr

It's possible to create a select input with a button or a link inside the options? I'd like to use it to list some values, and to have the option with a button to "Create Value" inside the options. I don't know if this is possible. I tried it with a href, but it treat it as text.

可以使用选项内的按钮或链接创建选择输入吗?我想用它来列出一些值,并在选项中使用带有“创建值”按钮的选项。我不知道这是否可能。我用 href 尝试过,但它把它当作文本。

This would be the ideal scenario:

这将是理想的场景:

<select name="things">
    <option value="1">Thing One</option>
    <option value="2">Thing Two</option>
    <option value="3">Thing Three</option>
    <option value=""><button>New Thing</button></option>
</select>

I've search, but with no luck. Does somebody knows an jQuery plugin or something like might work?

我已经搜索过,但没有运气。有人知道jQuery插件或类似的东西可能有用吗?

回答by p.s.w.g

Here's a simple implementation:

这是一个简单的实现:

$('select[name=things]').change(function() {
    if ($(this).val() == '')
    {
        var newThing = prompt('Enter a name for the new thing:');
        var newValue = $('option', this).length;
        $('<option>')
            .text(newThing)
            .attr('value', newValue)
            .insertBefore($('option[value=]', this));
        $(this).val(newValue);
    }
});

Of course, this could be done better, and more cleanly, but it's a start.

当然,这可以做得更好,更干净,但这是一个开始。

Demonstration

示范



After reading your comments, it appears you simply want to redirect the user to another form when they select a given option. In that case, you can simply do this:

阅读您的评论后,您似乎只想在用户选择给定选项时将其重定向到另一个表单。在这种情况下,您可以简单地执行以下操作:

$('select[name=things]').change(function() {
    if ($(this).val() == '')
    {
        window.location.href = 'CreateThingForm'; // Replace with the actual URL
    }
});

回答by Shehabic

You shouldn't do it this way, don't put button inside option.

你不应该这样做,不要把按钮放在选项里面。

alternatively you can :

或者你可以:

<select name="things" onchange="checkAndAddOption(this)">

or

或者

<select name="things" onclick="checkAndAddOption(this)">
.
.
.
</select>
<script>
function checkAndAddOption(selectElement) {
   if (selectElement.value === "") {
        var opt = document.createElement('option');
        opt.value = 'newVal';
        opt.innerHTML = 'textToDisplay';
        selectElement.appendChild(opt);
   }
}
</script>