繁体   English   中英

从selectize.js获取ID以形成表单

[英]Get ID from selectize.js to form

我正在尝试在我的网站上设置一个表单,并希望使用一些动态下拉菜单。

我找到了Selectize.js,这似乎是一个不错的解决方案,但是当我发布表单时,我一直在努力寻找如何从所选选项中获取ID的方法。

如用户选择“香蕉”并选择应返回2作为帖子的值

显而易见的答案当然是将valueField更改为'id'但是这会弄乱createFilter所以这是不行的。

到目前为止,我已经做了一个jsfiddle: http : //jsfiddle.net/imfpa/Lh3anheq/16/

HTML:

<form>
    <select id="item-type" placeholder="Choose type...">
    </select>
</form>

javascript:

function hasOwnPropertyCaseInsensitive(obj, property) {
    var props = [];
    for (var i in obj) if (obj.hasOwnProperty(i)) props.push(i);
    var prop;
    while (prop = props.pop()) if (prop.toLowerCase() === property.toLowerCase()) return true;
    return false;
}

var REGEX = '[a-zA-ZæøåÆØÅ][a-zA-ZæøåÆØÅ ]*[a-zA-ZæøåÆØÅ]';

$('#item-type').selectize({
    persist: true,
    valueField: 'text',
    labelField: 'text',
    searchField: ['text'],
    options: [
        {id: '1', text: 'Apple'},
        {id: '2', text: 'Banana'},
        {id: '3', text: 'Orange'},
        {id: '4', text: 'Cherry'},

    ],    

    createFilter: function(input) {
        var match, regex;

        regex = new RegExp('^' + REGEX + '$', 'i');
        match = input.match(regex);
        if (match) {
        console.log(match[0]);
            return !hasOwnPropertyCaseInsensitive(this.options, match[0]);
        }

        return false;
    },
    create: true
});  

jsFiddle演示http://jsfiddle.net/json/Lh3anheq/35/

好的,基于上面评论中的讨论,您希望selectize.js返回所选项目的id ,并允许用户创建唯一的项目。

您对id是正确的:您只需要将valueField: 'text'替换为valueField: 'id'

现在,我们需要修复函数hasOwnPropertyCaseInsensitive的决策。 此函数中的第一个参数是对象的对象。 如果您看到控制台输出,则对于this.options元素的selectize ,您将大致看到以下结构( valueField已被id替换):

{
    idOfItem1: {
        id: idOfItem1,
        text: textOfItem1
    },
    idOfItem2: ...
}

这是Web检查器为console.log(this.options)打印的console.log(this.options)

控制台输出

因此,我们可以遍历所有对象,并且仍然在字段text具有显示值 ,而这正是我们需要与用户输入进行比较以唯一性的字符串。

function hasOwnPropertyCaseInsensitive(options, userValue) {
    var exists = false;

    for (var option in options) {
        if (options.hasOwnProperty(option)) {
            if (options[option].text.toLowerCase() === userValue.toLowerCase()) {
                exists = true;
                break; // break from the loop when the match is found. return true works as well.
            }
        }   
    }

    return exists;
}

注意! 用户创建的元素的id将与显示值相同。 即,如果我向列表中添加一个新元素,例如Test ,它将看起来像这样:

{
    Test: {
        id: "Test",
        text: "Test"
    }
}

请查看jsFiddle演示http://jsfiddle.net/json/Lh3anheq/35/ ),让我知道是否错过了一些东西。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM