【问题标题】:jqgrid retrieve data of cell and manipulate itjqgrid 检索单元格的数据并对其进行操作
【发布时间】:2011-05-23 09:05:00
【问题描述】:

我想从dataEvents 事件中检索用户输入的值。我只想允许数字 0-24,如果用户插入像 4,5(德语写作)这样的数字,我想用“。”替换“,”。因此将“4,5”转换为“4.5”。

但我正在努力获取用户输入的数据。我使用的方法总是返回空白。

colModel:[
    {name:'sum',index:'sum', width:45, editable: true, sortable:false,
     editoptions: { dataEvents: [ 
                        {
                            type: 'keypress', // keydown
                            fn: function(e) {
                                // console.log('keypress');
                                var v=$(e.target).text();
                                alert(v); // v is empty.
                                //reset the target value, actually I want to replace
                                // enter code here a comma with a point
                                // only allow the numbers 0 - 24
                            }
                        }
                    ] 
                  }
    },
],

【问题讨论】:

    标签: jquery jqgrid


    【解决方案1】:

    您可以将 ',' 替换为 '.'更好地在“keyup”事件处理程序中使用以下内容

    $(this).val($(this).val().replace(/,/,'.'));
    

    所以你可以使用以下dataEvents

    dataEvents: [
        {
            type: 'keyup',
            fn: function(e) {
                var oldVal = $(this).val();
                var newVal = oldVal.replace(/,/,'.');
                if (oldVal !== newVal) {
                    $(this).val(newVal);
                }
            }
        },
        {
            type: 'keypress',
            fn: function(e) {
                var key = e.charCode || e.keyCode; // to support all browsers
                if((key < 48 || key > 57) &&   // if non digit
                   key !== 46 && key !== 44 && key !== 8 && // and not . or , or backspace
                   key !== 37 && key !== 39) { // arrow left and arrow right
                    return false;
                }
            }
        }
    ]
    

    the following demo 上,您可以实时查看结果。我在示例中看到的唯一缺点如下:如果您尝试在文本中间键入逗号 ,光标位置(插入符号)将在替换逗号指向。在你的情况下,这可能不是一个真正的问题。如果您确实想保存光标位置,您可能应该这样做 document.selection 用于 IE 或 .selectionStart.selectionEnd 用于 Firefox。

    更新:我修复了在 Firefox 中 keypress 事件中使用 e.keyCode 的问题。我遵循来自here 的信息,现在使用e.charCode || e.keyCode 而不是e.keyCode。上述代码和演示现已修复。

    【讨论】:

    • 奥列格,这太棒了!我稍后会尝试,但现场演示(哇,得到现场演示)已经正是我想要的!
    • 谢谢奥列格。它工作得很好!你拯救了我的周末;-)
    • @Oleg:我刚刚认识到,如果使用 firefox,用户无法在单元格中插入数字,而在 chrome 中它可以工作。你知道如何规避这个问题!?
    • @Tom Tom:明天我会试着看看这个问题。
    • @Tom Tom:我在您描述的 Firefox 中找到了问题的原因并修复了代码。最好的问候。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-17
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    相关资源
    最近更新 更多