I have an input element in HTML markup as below:
<input type="text" name="s" id="s" value="" />
I am changing the characters entered in this input element with Urdu ones (like a mini virtual keyboard), by using jQuery’s keypress:
$("#s").keypress(function(e) {
var pos = getCaretPos('s');
// key-mapping logic here
});
I also have some buttons that help a user enter their desired Urdu character by clicking on a respective button. Thus:
// Process clicks on buttons with class=kb-letter
$(".kb-letter").click(function() {
var pos = getCaretPos('s');
// logic for entering Urdu characters in 's' here
});
This is the function for getting caret position. It returns the current caret position in s and the new character is then inserted at that position:
function getCaretPos(areaId) {
var txtArea = document.getElementById(areaId);
var pos = 0;
var br = (document.selection ? "ie" : ((txtArea.selectionStart || txtArea.selectionStart == '0') ? "ff" : false ) );
if (br == "ie") {
txtArea.focus();
var range = document.selection.createRange();
range.moveStart ('character', -txtArea.value.length);
pos = range.text.length;
}
else if (br == "ff") {
pos = txtArea.selectionStart;
}
return pos;
}
Now, the above getCaretPos() works fine in Firefox 8 and Chrome 17 for both direct keyboard input in s and input using clicking on buttons; but on Internet Explorer 8, it works only for direct keyboard input. If I try entering a character using mouse clicks, it gets entered at location 0 because getCaretPos() always returns 0 in that case.
I have no idea what is going wrong. Do I need to call getCaretPos() in a different manner in response to mouse clicks for IE?
Never mind. I was using an unordered list with its
<li>s posing as keyboard buttons. For some reason, IE was having problems with them. I swapped the<li>s for<button>s and nowgetCaretPos()is working all fine.