jqgrid retrieve data of cell and manipulate it

前端 未结 1 453
無奈伤痛
無奈伤痛 2020-12-06 15:55

I want to retrieve from a dataEvents event the value the user entered. I want to only allow the numbers 0-24 and if the user inserts a number like 4,5 (german w

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-06 16:35

    You can do replacement of ',' to '.' better inside of 'keyup' event handler with the following

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

    So you can use following 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;
                }
            }
        }
    ]
    

    On the following demo you can see the results live. The only disadvantage which I see in the example is following: if you will try to type comma in the middle of the text, the cursor position (caret) will be changed to the end of the input after the replacement comma to point. Probably it is not a real problem in your case. It you do want to save the cursor position you should probably do this document.selection using for IE or .selectionStart and .selectionEnd for Firefox.

    UPDATED: I fixed the problem with the usage of e.keyCode inside of keypress event in the Firefox. I follows the information from here and use now e.charCode || e.keyCode instead of e.keyCode. The above code and the demo are fixed now.

    0 讨论(0)
提交回复
热议问题