Sometimes, we need to check which key was pressed or what exact data was entered in the textbox and then take various actions like show it on other control or block that character.
But the problem with
KeyPress
event is that when this event occurs, recent entered character is not got in textbox value.
Let me explain this through an example: suppose we entered in textbox ‘
H
’ then on
keypress
event control show blank and when we entered ‘
I
’ then show only ‘
H
’, it means in
Keypress
event only show textbox previous entered text with current character.
<asp:TextBox ID="txtName" onkeypress="showContent()" ClientIDMode="Static" runat="server"></asp:TextBox>
<label id="lblPrview" ></label>
<script type="text/javascript">
function showContent() {
// assign value using jQuery
//$('#lblPrview').html($('#txtName').val());
// assign value using js
document.getElementById('lblPrview').innerHTML = document.getElementById('txtName').value;
}
</script>
Solution
In the below JavaScript code, by using
String.fromCharCode()
method, we get the current entered character.
<asp:TextBox ID="txtName" onkeypress="showContent(event)" ClientIDMode="Static" runat="server"></asp:TextBox>
<label id="lblPrview" ></label>
<script type="text/javascript">
function showContent(e) {
var recentChar = String.fromCharCode(e.which);
//select textbox value using jQuery
//var ctlValue = $('#txtName').val();
//select textbox value using js
var ctlValue = document.getElementById('txtName').value;
var completetext = ctlValue + recentChar;
// assign value using jQuery
// $('#lblPrview').html(completetext);
// assign value using js
document.getElementById('lblPrview').innerHTML = completetext;
}
</script>
We can manage this functionality with other events like
keyup
, but this is only related to
Keypress
events.