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

时间:2014-01-17 23:36:52

标签: javascript jquery html html5

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

这将是理想的情况:

<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>

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

3 个答案:

答案 0 :(得分:6)

这是一个简单的实现:

$('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);
    }
});

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

Demonstration


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

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

答案 1 :(得分:1)

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

或者你可以:

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

<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>

答案 2 :(得分:0)

我想推荐this,可能需要组合框。它实际上可以做很多事情。