繁体   English   中英

为什么Select2更改事件触发表单提交?

[英]Why Select2 change event fires form submit?

我有一个带有select2的标记系统构建,其中用户应该能够选择现有标记或添加新标记。 我的代码的简化版本如下所示:

$('input').select2({
    tags: [
        {id:0, text:'red', status:'old'},
        {id:1, text:'green', status:'old'},
        {id:2, text:'blue', status:'old'}
    ],
    tokenSeparators: [","],
    createSearchChoice: function (term, data) {
        return {id: term, text: term, status: 'new'};
    }
}).change(function(e) {
    if (e.added && e.added.status == 'new') {
        if (confirm('Not found. Add?')) {
            // Add new tag to database.
        }
    }
});

这是示例( 示例1 )如何工作。 (用户可以添加现有标签“红色”,“绿色”和“蓝色”。createSearchChoice-function允许用户创建新标签。)在此示例中,检测到新标签时,.change()-event中不执行任何操作。 一切正常。

但是,就像上面的代码块一样,添加新标签后,我想确认用户是否确实要添加新标签。 问题是当我在检测到新标签的方括号中添加确认代码时,表单提交事件触发。 这是此行为的示例( 示例2 )。 只需尝试添加不存在的标签。

现在我的问题是:

  1. 为什么要提交表单?
  2. 我该如何防止这种行为?

我正在使用select2 3.4.0和jQuery 2.0.2

一种解释是,当确认功能停止执行更改事件时,浏览器继续其工作,并运行表单提交处理程序,该处理程序在用户选择新标签时按下Enter键时触发。 通常,select2会阻止此执行,但是在这种情况下,它会被确认功能阻止。

现在,如果将确认逻辑移到它自己的单独函数并从setTimeout-function中调用,则change-event将正常执行,并且select2阻止表单提交。

$('input').select2({
    tags: [
        {id:0, text:'red', status:'old'},
        {id:1, text:'green', status:'old'},
        {id:2, text:'blue', status:'old'}
    ],
    tokenSeparators: [","],
    createSearchChoice: function (term, data) {
       return {id: term, text: term, status: 'new'};
    }
}).change(function(e) {
    if (e.added && e.added.status == 'new') {
        setTimeout(myConfirm,50);
    }
});

function myConfirm() {
    if (confirm('Not found. Add?')) {
        // Add new tag to database.
    }
}

这是此解决方案的示例

其他解释和解决方案仍然受到高度赞赏!

暂无
暂无

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

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