Reputation: 968
Here is the scenario:
I am trying to show indication "XY characters left" and also limit characters in texbox as user types. I have multiline teboxes too, so MaxLength doesn't always work for me (don't worry, I check on server side too).
Here is what I have learned: onkeyup works perfectly with this function:
function LimtCharacters(txtMsg, CharLength, indicator) {
chars = txtMsg.value.length;
document.getElementById(indicator).innerHTML = CharLength - chars;
if (chars > CharLength) {
txtMsg.value = txtMsg.value.substring(0, CharLength);
}
}
But, I also need to detect pasted values. If user uses CTRL+V it's OK, but this doesn't work if user pastes using mouse. I have learned, that in this case we need delay (here): Javascript OnPaste
So, I updated (added onPaste event) like this:
/* FUNCTION THAT LIMITS INSERTED CHARACTERS IN TEXTBOX */
function LimtCharacters(txtMsg, CharLength, indicator) {
chars = txtMsg.value.length;
document.getElementById(indicator).innerHTML = CharLength - chars;
if (chars > CharLength) {
txtMsg.value = txtMsg.value.substring(0, CharLength);
}
}
/* Delay is needed if user uses paste with mouse (right click and paste). After delay same function (LimtCharacters) can be called*/
function pasted(txtMsg, CharLength, indicator) {
setTimeout(function () {
LimtCharacters(txtMsg, CharLength, indicator);
}, 10);
}
Markup in ASPX file:
<asp:TextBox ID="tbTitle" runat="server" ClientIDMode="Static" MaxLength="255"
onKeyup="LimtCharacters(this,255,'lblTitleCount')"
onPaste="pasted(this,255,'lblTitleCount')" />
<asp:Label ID="lblTitleCount" Text="255" runat="server" ClientIDMode="Static" />
lblTitle is the label that displays "characters left" value.
It works perfect in FireFox and Chrome. But it doesn't work in IE.
What am I doing wrong?
I am using visual studio 2010 .net.
Any hint/help would be greatly appreciated ;)
Upvotes: 1
Views: 7028
Reputation: 565
<script type="text/javascript">
$(document).ready(function () {
$("#tbTitle").on("input", function () {
LimtCharacters(this, 255, 'lblTitleCount');
});
});
</script>
//FUNCTION THAT LIMITS INSERTED CHARACTERS IN TEXTBOX
function LimtCharacters(txtMsg, CharLength, indicator){
chars = txtMsg.value.length;
document.getElementById(indicator).innerHTML = CharLength - chars;
if (chars > CharLength) {
txtMsg.value = txtMsg.value.substring(0, CharLength);
//Text in textbox was trimmed, re-set indicator value to 0
document.getElementById(indicator).innerHTML = 0;
}
}
Upvotes: 2