If I press (for the first time) a character, than the alert prints an empty value.
How is possible? I don't understand.
$('#search-vulc').on('keydown', function() {
var textinsert = ($(this).val()).toLowerCase();
alert(textinsert);
});
Please tell me how I can print it with the first time, when the character is pressed.
Here is there also a jsfiddle example:
/
If I press (for the first time) a character, than the alert prints an empty value.
How is possible? I don't understand.
$('#search-vulc').on('keydown', function() {
var textinsert = ($(this).val()).toLowerCase();
alert(textinsert);
});
Please tell me how I can print it with the first time, when the character is pressed.
Here is there also a jsfiddle example:
https://jsfiddle/06xg4c78/1/
Share Improve this question edited Jun 5, 2018 at 7:51 Michel 4,1574 gold badges37 silver badges56 bronze badges asked Jun 13, 2016 at 13:16 BorjaBorja 3,5797 gold badges38 silver badges75 bronze badges 7-
8
keydown event occures before the value is updating, use
keyup
orinput
event instead – Pranav C Balan Commented Jun 13, 2016 at 13:17 - Use console.log to debug, not alert – j08691 Commented Jun 13, 2016 at 13:18
- @PranavCBalan how kind of form event ? maybe change() ? – Borja Commented Jun 13, 2016 at 13:19
- @Borja : which fires when you leave focus in case of text field – Pranav C Balan Commented Jun 13, 2016 at 13:20
- 1 @PranavCBalan ok thanks a lot for the suggest ;) – Borja Commented Jun 13, 2016 at 13:21
3 Answers
Reset to default 3Use keuyp event:
This is because keypress events
are fired before the new character is added to the value of the element (so the first keypress event
is fired before the first character is added, while the value is still empty). You should use keyup
instead, which is fired after the character has been added.
$('#search-vulc').on('keyup', function() {
var textinsert = ($(this).val()).toLowerCase();
alert(textinsert);
});
Use keyup
instead:
$('#search-vulc').on('keyup', function() {
var textinsert = ($(this).val()).toLowerCase();
alert(textinsert);
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" size="150" style="width: 150px;" name="qu" id="search-vulc">
Updated fiddle: https://jsfiddle/06xg4c78/2/
if you use keydown
functions it works before dom gets the input value
Use keyup
which fires the event when you leave the key so it will get the value entered
$('#search-vulc').on('keyup', function() {
var textinsert = ($(this).val()).toLowerCase();
alert(textinsert);
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" size="150" style="width: 150px;" name="qu" id="search-vulc">