简体   繁体   English

Select2更改输入名称(如果正在提交标签)

[英]Select2 change input name if tag is being submited

So I have the following select2: 所以我有以下select2:

productFamilySelect.select2({
            tags: true
        });

By default the name of the associated select element is product_family_id , so is there a way to change the name of the input to lets say product_family_name , if selected value if one that user entered? 默认情况下,关联的select元素的名称为product_family_id ,是否有一种方法可以将输入的名称更改为让我们说product_family_name ,如果用户输入了一个选定的值? This is so, that I could in the backend for sure distinguish between an already existing value, and one that user thought of. 这样,我就可以肯定地在后端区分一个已经存在的值和一个用户想到的值。 Checking by id in the database does not really suit, as this value could actually be numeric in on itself. 通过数据库中的id进行检查并不十分适合,因为该值本身实际上可以是数字。

After some digging into select2 custom events I found a way: 在深入研究select2自定义事件后,我找到了一种方法:

firstly add createTag callback like so: 首先添加createTag回调,如下所示:

productFamilySelect.select2({
            tags: true,
            createTag: function (params) {
                var term = $.trim(params.term);

                if (term === '') {
                    return null;
                }
                return {
                    id: term,
                    text: term,
                    newTag: true
                }
            }
        });

Then, add the following listener: 然后,添加以下侦听器:

productFamilySelect.on('select2:select', function (e) {
            if (e.params.data.newTag === true) {
                $(this).attr('name', 'product_family_name');
            } else {
                $(this).attr('name', 'product_family_id');
            }
        });

Seems a bit hacky, since it is outside the config of the actual select2 config, but well it dos the job :) 似乎有点骇人听闻,因为它不在实际的select2配置的配置中,但是它确实可以完成工作:)

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

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