Добавление маски в столбец jqGrid на строку редактирования - PullRequest
1 голос
/ 10 марта 2020

Мне нужно создать маску телефона для некоторых столбцов, когда я добавляю или редактирую запись, используя jqGrid (моя версия jqGrid - 4.5.4).

Ниже моего кода:

this.montarGRID = function (p_gridName, p_dados, p_header, p_descriptor, p_contentName, p_primaryKey, p_filtroGrid) {
jQuery("#" + p_gridName).jqGrid( {
    data : p_dados, 
    datatype : "local", 
    sortable : true, 
    colNames : p_header, 
    colModel : p_descriptor,
...

Эта сетка генерируется динамически. Я передаю json с содержимым colModel.

[
{"formatter":"integer","index":"id","hidden":true,"sortable":true,"sorttype":"integer","width":75,"align":"center","name":"id"},
{"formatter":"telefone","index":"TELCONTATO01","search":true,"hidden":false,"sorttype":"text","sortable":true,"width":0,"align":"right","name":"TELCONTATO01","editoptions":{"text":true,"required":false,"dataInit":"function (elem) {  return mostra_telefone(elem); }"},"editrules":{"text":true,"required":false,"dataInit":"function (elem) {  return mostra_telefone(elem); }"},"editable":true},
{"formatter":"telefone","index":"TELCONTATO02","search":true,"hidden":false,"sorttype":"text","sortable":true,"width":0,"align":"right","name":"TELCONTATO02","editoptions":{"text":true,"required":false,"dataInit":"function (elem) {  return mostra_telefone(elem); }"},"editrules":{"text":true,"required":false,"dataInit":"function (elem) {  return mostra_telefone(elem); }"},"editable":true}
]

метод, который генерирует маску телефона ...

(function($) {
    'use strict';
    $.extend($.fn.fmatter, {
        mostra_telefone : function (elem) {
            $(elem).mask("(99)9999-9999?");
        }
    });
})(jQuery);

Но он никогда не вызывается при выборе, изменении или добавьте запись.

Ответы [ 2 ]

0 голосов
/ 13 марта 2020

Я решил проблему с этим:

function custom_element_telefone(value, options){
    var el = document.createElement("input");
    el.type="text";
    el.value = value;
    $(el).addClass('inline-edit-cell ui-widget-content ui-corner-all').inputmask({"mask": "(99)9999-9999#"});
    return el;
};

this.montarGRID = function (p_gridName, p_dados, p_header, p_descriptor, p_contentName, p_primaryKey, p_filtroGrid) {

    p_descriptor.forEach(col => {
        if (!col.editoptions) return;
        if (!col.editoptions.custom_element) return;

        switch (col.editoptions.custom_element) {
            case "custom_element_telefone":
                col.editoptions.custom_element = custom_element_telefone;
                break;            
        }
    });

    jQuery("#" + p_gridName).jqGrid( {
        data : p_dados, 
        datatype : "local", 
        sortable : true, 
        colNames : p_header, 
        colModel : p_descriptor,
...
0 голосов
/ 12 марта 2020

Вот кусок кода, который выполняет желаемое поведение. Для этого мы используем плагин inputpask. $ ("# jqGrid"). jqGrid ({... colModel: [

                {
                    name: 'Telephone',
                    width: 100,
                    formatter: function(cellvalue, options, rowObject) {
                        var re = new RegExp("([0-9]{3})([0-9]{3})([0-9]{4,6})", "g");
                        return cellvalue.replace(re, "($1) $2-$3"); 
                    },
                    unformat : function(cellvalue, options, rowObject) {
                        return cellvalue.replace("(",'').replace(") ",'').replace("-",'');
                    },
                    editable: true,
                    edittype: "custom",
                    editoptions :{
                        custom_element : function(value, options) {
                            var el = document.createElement("input");
                            el.type="text";
                            el.value = value;
                            $(el).addClass('inline-edit-cell ui-widget-content ui-corner-all').inputmask({"mask": "(999) 999-9999"});
                            return el;                              
                        },
                        custom_value : function(elem, operation, value) {
                            if(operation === 'get') {
                                return $(elem).val().replace("(",'').replace(") ",'').replace("-",'').replace(/\_/g,'');;
                            } else if(operation === 'set') {
                                $(elem).val(value);
                            }                               
                        }
                    },
                    editrules : {
                        requiered : true,
                        custom : true,
                        custom_func : function(val, name) {
                            // special replace mask at end
                            var cel  = val.replace("(",'').replace(") ",'').replace("-",'').replace(/\_/g,'');
                            if(cel.length !== 10) {
                                return [false,"Please, enter correct phone number"];
                            } 
                            return [true,""];
                        }
                    }   
                },                  

          ....
       ],
    ....
});

Этот код также должен работать в вашей версии. Также здесь есть ссылка на демонстрационную версию .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...