Trying to do some jQuery validation (without the plugin - please no answers like "Just use the validate-js plugin").
I'm wiring up a client-side event handler keypress for each "required field" on doc ready:
$(document).ready(function() {
$('#myform input.required').each(function() {
$(this).keypress(onRequiredFieldKeyPress);
});
});
Which correctly fires this event on each keypress:
function onRequiredFieldKeyPress() {
if ($(this).val().trim() == '') {
$(this).next('em').html('*').show(); // show req field indicator
} else {
$(this).next('em').html('*').hide(); // hide req field indicator
}
}
But $(this).val() is always null/empty. Looks like it's passing in an "HTMLInputElement" which is what i'd expect, but it's almost like i have to project this into some other jQuery type?
Essentially i'm trying to do this: on the keypress event of any field which i have wired-up (which are all input elements), call that function. In that function, if that field has a value of '' (empty), then show a hidden field which displays a required field indicator.
I don't really care which actual element fired the keypress, as the behaviour of my logic will be the same. I just need to get the actual value.
Am i missing something?
3. Which property is used to specify the key type when pressed? Explanation: The keyCode property returns the Unicode character code of the key that triggered the onkeypress event, or the Unicode key code of the key that triggered the onkeydown or onkeyup event.
The simple solution: just use the keyup event (and not the keydown event). This will give you the latest value after the user typed the latest character. That resolves the issue.
The keypress() method in jQuery triggers the keypress event whenever browser registers a keyboard input. So, Using keypress() method it can be detected if any key is pressed or not.
The keypress() method triggers the keypress event, or attaches a function to run when a keypress event occurs. The keypress event is similar to the keydown event. The event occurs when a button is pressed down.
Because you are using key-press event. Key press has 3 phase:
1. Key down: when key is press
2. Key hold: key is hold down
3. Key up: key is release
In your case, problem can be solved by using keyup event
$(document).ready(function() {
$('#myform input.required').each(function() {
$(this).keyup(onRequiredFieldKeyPress);
});
});
Try using event.currentTarget, where event is the first param of your function.
See here: http://api.jquery.com/event.currentTarget
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With