English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Recently, there was a requirement that when entering a tax number, it needs to be automatically converted to half-width uppercase, and the input of punctuation symbols and Chinese characters should be prevented. (The following content includes: full-width and half-width conversion, text box selection, cursor position judgment, setting cursor position, etc.)
First, I checked the difference between full-width and half-width and how to convert them.
var str = "中文;;a";
if (str[i].match(++) { [\u0000/\u00ff]-/)) { else if (str[i].match( }/[\uff00-\uffff]/)) { console.log("Full-width character " + str[i] + " " + toSBC(str[i])); } else { console.log(str[i]); // Texts other than numbers and English, including Chinese and other languages. } }
This is the difference between the two, convert the text to unicode and compare them. Both have their own range, half-width is 0x20~0x7E, full-width is 0xFF01~0xFF5E. (This is16The prefix 0x represents hexadecimal.16(decimal)}
Conversion, except for the space, is the same as full-width-Half-width=65248(0xFEE0)
The specific conversion function is as follows: (This is a relatively reliable method found on the Internet, but the methods on the Internet generally write SBC and DBC in reverse, so I have corrected it here.)
// Convert full-width characters function toSBC(str) { var result = ""; var len = str.length; for (var i = 0; i < len; i++) { var cCode = str.charCodeAt(i); //Full-width and half-width difference (except for spaces):65248(decimal) cCode = (cCode>=0x0021 && cCode<=0x007E)?(cCode + 65248) : cCode; //handle spaces cCode = (cCode==0x0020)?0x03000:cCode; result += String.fromCharCode(cCode); } return result; } // Convert half-width characters function toDBC(str) { var result = ""; var len = str.length; for (var i = 0; i < len; i++) { var cCode = str.charCodeAt(i); //Full-width and half-width difference (except for spaces):65248(Decimal) cCode = (cCode>=0xFF01 && cCode<=0xFF5E)?(cCode - 65248) : cCode; //handle spaces cCode = (cCode==0x03000)?0x0020:cCode; result += String.fromCharCode(cCode); } return result; }
The difference between full-width and half-width has been found, and now we are thinking of ways to convert it, using the input method.
var oldValue = ""; var $thisDom; // Suppose there is a jQuery DOM element $thisDom.unbind().bind("input", function (e) { var reg = /^[0-9A-Za-z]*$/; var str = toDBC(e.target.value).toUpperCase(); if (reg.test(str)) { oldValue = str; $(this).val(str); } else { $(this).val(oldValue); } });
However, there is a problem, that is, the cursor has a problem. There is no problem when inputting at the last digit, but when inputting in the middle, the cursor always jumps to the last digit. Then there are the following related cursor knowledge.
The following related code was found on the Internet, used to control the cursor position.
function getCursortPosition(ctrl){ var CaretPos = 0; if (document.selection) { ctrl.focus(); var Sel = document.selection.createRange(); Sel.moveStart('character', -ctrl.value.length); CaretPos = Sel.text.length; } else if (ctrl.selectionStart || ctrl.selectionStart == '0') { CaretPos = ctrl.selectionStart; } return (CaretPos); } function setCaretPosition(ctrl, pos){ if (ctrl.setSelectionRange) { ctrl.focus(); ctrl.setSelectionRange(pos, pos); } else if (ctrl.createTextRange) { var range = ctrl.createTextRange(); range.collapse(true);}} range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } }
These two are to get the cursor position and to set the cursor position. Here we use the textRange object.
The TextRange object is an advanced feature of Dynamic HTML (DHTML), which can be used to perform many text-related tasks, such as searching and selecting text. Text range allows you to selectively pick out characters, words, and sentences from the document. The TextRange object is an abstract object that establishes the start and end positions on the text stream of the HTML document to be displayed.
The following are the commonly used properties and methods of TextRange:
Properties:
boundingHeight Get the height of the rectangle bound by the TextRange object
boundingLeft Get the distance between the left edge of the rectangle bound by the TextRange object and the left edge of the TextRange object that contains it
offsetLeft Get the computed left position of the object relative to the page or the parent coordinate specified by the offsetParent property
offsetTop Get the computed top position of the object relative to the page or the parent coordinate specified by the offsetParent property
htmlText Get the width of the rectangle of the bound TextRange object
text Set or get the text contained within the range
Method:
moveStart - Change the start position of the range
moveEnd - Change the end position of the range
collapse - Move the insertion point to the beginning or end of the current range
move - Fold the given text range and move the empty range by the given number of units
execCommand - Execute the command on the current document, current selection area, or given range
select - Set the current selection area to the current object
findText - Search for text in the text and set the start and end points of the range to enclose the search string.
For specific usage, see other people's articles, the address is: https://www.oldtoolbag.com/article/105787.htm
Returning to the topic, I integrated the above code into my code.
function toDBC(str) { var result = ""; var len = str.length; for (var i = 0; i < len; i++) { var cCode = str.charCodeAt(i); //Full-width and half-width difference (except for spaces):65248(Decimal) cCode = (cCode>=0xFF01 && cCode<=0xFF5E)?(cCode - 65248) : cCode; //handle spaces cCode = (cCode==0x03000)?0x0020:cCode; result += String.fromCharCode(cCode); } return result; } function getCursortPosition(ctrl){ var CaretPos = 0; if (document.selection) { ctrl.focus(); var Sel = document.selection.createRange(); Sel.moveStart('character', -ctrl.value.length); CaretPos = Sel.text.length; } else if (ctrl.selectionStart || ctrl.selectionStart == '0') { CaretPos = ctrl.selectionStart; } return (CaretPos); } function setCaretPosition(ctrl, pos){ if (ctrl.setSelectionRange) { ctrl.focus(); ctrl.setSelectionRange(pos, pos); } else if (ctrl.createTextRange) { var range = ctrl.createTextRange(); range.collapse(true);}} range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } } var oldValue = this.model.get("taxNo"); $taxNoDom.unbind().bind("input", function (e) { var reg = /^[0-9A-Za-z]*$/; var position = getCursortPosition($taxNoDom[0]); var str = toDBC(e.target.value).toUpperCase(); if (reg.test(str) && str.length <= 25) { oldValue = str; $(this).val(str); setCaretPosition($taxNoDom[0], position); } else { $(this).val(oldValue); setCaretPosition($taxNoDom[0], position - 1); } });
In the above code, the binding event I wrote is at the bottom, and it should be understandable if you look carefully. However, there is a bug in the above code, which is actually a bug in the getCursortPosition method.
That is, when typing in Chinese input method, the letters entered are in selected format when the input event is executed, the cursor is before the letter, and the position is deviated from the imagination, so the correct characters are always printed after the cursor.
At that time, I was very distressed and felt that life was meaningless... I thought of several methods:
1. Default trigger keyboard left arrow and then trigger right arrow. This should be the correct position regardless of whether the cursor is selected.
2. Check if there is selected text in the current page. If there is selected text, return the cursor position+1.
I searched online for the first method and immediately gave up. There is also very little related information, and the limitations are quite large, with significant differences between browsers, so it does not seem to be a good method at all.
Then I found the second method, which is window.getSelection and document.selection
IE9Below support: document.selection
IE9, Firefox, Safari, Chrome, and Opera support: window.getSelection()
(Since our company project only supports ie9and above, there is no attempt to use document.selection)
I tried it myself, when there is selected text, window.getSelection().type === "Range", and if there is no selection, window.getSelection().type === "Caret".
Thus, the final code is as follows:
function toDBC(str) { var result = ""; var len = str.length; for (var i = 0; i < len; i++) { var cCode = str.charCodeAt(i); //Full-width and half-width difference (except for spaces):65248(Decimal) cCode = (cCode>=0xFF01 && cCode<=0xFF5E)?(cCode - 65248) : cCode; //handle spaces cCode = (cCode==0x03000)?0x0020:cCode; result += String.fromCharCode(cCode); } return result; } function getCursortPosition(ctrl){ var CaretPos = 0; if (document.selection) { ctrl.focus(); var Sel = document.selection.createRange(); Sel.moveStart('character', -ctrl.value.length); CaretPos = Sel.text.length; } else if (ctrl.selectionStart || ctrl.selectionStart == '0') { if (window.getSelection().type === "Range") { CaretPos = ctrl.selectionStart + 1; } else { CaretPos = ctrl.selectionStart; } } return (CaretPos); } function setCaretPosition(ctrl, pos){ if (ctrl.setSelectionRange) { ctrl.focus(); ctrl.setSelectionRange(pos, pos); } else if (ctrl.createTextRange) { var range = ctrl.createTextRange(); range.collapse(true);}} range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } } var oldValue = this.model.get("commercialTax").taxNo; $taxNoDom.unbind().bind("input", function (e) { var reg = /^[0-9A-Za-z]*$/; var position = getCursortPosition($taxNoDom[0]); var str = toDBC(e.target.value).toUpperCase(); if (reg.test(str) && str.length <= 25) { oldValue = str; $(this).val(str); setCaretPosition($taxNoDom[0], position); } else { $(this).val(oldValue); setCaretPosition($taxNoDom[0], position - 1); } });
That's all for this article. I hope the content of this article can bring some help to everyone's learning or work, and I also hope to get more support for the呐喊 tutorial!
Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)