开发者

jqgrid retrieve data of cell and manipulate it

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 writing开发者_开发知识库) I want to replace the "," with a ".". Thus convert "4,5" to "4.5".

But I'm struggling with getting the data the user entered. The method I'm using always returns blank.

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
                            }
                        }
                    ] 
                  }
    },
],


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜