select2 on success retrieve newly created tag id

北战南征 提交于 2019-12-06 07:35:58

As you have said, you can replace that value, and that is what my solution does. If you search the Element Inspector of Chrome, you will see, bellow the Select2 field, an input with the id project_tags and the height of 1.

The weird thing is that the element inspector of Chrome does not show you the values of the input, as you can see below:

However, you do a console.log($("#project_tags").val()) the input has values (as you see in the image).

So, you can simply replace the text of the new option by the id, inside the success function of the ajax call placed within the $('#project_tags').on("change") function. The ajax call will be something like:

$.ajax({
    url: 'framework/helpers/tags.php',
    data: {
        action: 'add',
        term: e.added.id
    },
    success: function(tag_id) {
        var new_val = $("#project_tags")
                        .val()
                        .replace(e.added.id, tag_id);
        $("#project_tags").val(new_val);
    },
    error: function() {
        alert("error");
    }
});

Please be aware that this solution is not bullet proof. For example, if you have a tag with the value 1 selected, and the user inserts the text 1, this will cause problems.

Maybe a better option would be replace everything at the right of the last comma. However, even this might have cause some problems, if you allow the user to create a tag with a comma.

Let me know if you need any more information.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!