This question already has answers here:
onkeyup and onfocusout is not working in jQuery Validate
(1 answer)
jQuery validate plugin: validate on blur() by default
(1 answer)
Closed 5 years ago.
I'm making a "contact me" page, with jQuery validation. My main content box is reloaded with ajax to change content when the user clicks on a new page. The problem I'm having now is to bind an event handler for the validate function. what I got now is
$(document).ready(function(){
$('body').bind('focus focusout keyup', function() {
$('#contact_me').validate({
But it's not working like intended. I have to start typing, then click out of the input field and then click on it again before it starts to validate the input field value. I want it to validate on focus, focusout and keyup. I think the problem is with the event handler somehow. Any suggestions?
Here is a JSfiddle with the script: https://jsfiddle.net/z6h9d028/4/
I can see now that the eventhandler is not the problem. When i type in a input field its not validating the value until i click out of the box. After the first validation i works on keyup as well. How can i get i to work on keyup stright away?
Edit 2:
Updated fiddle: https://jsfiddle.net/z6h9d028/7/
It's almost working now! I just need to get all the error messages to show when clicking the submit button. And to find a way to show the error message when you type one character and then remove it if the input field is required (it does show it if you type once, then remove, type again and remove. but not the first time)
You don't need to set your own event listeners, or at least if you do, you shouldn't be using them on the .validate() method (see alternative method below).
Remove the whole $('body').bind() part, and add the following to your validate settings object:
onkeyup: function(element) {
$(element).valid();
// As sparky mentions, this could cause infinite loops, should be this:
// this.element(element);
},
This should be better too, as it may give you some extra freedom as to how you handle the onkeyup events, such as adding a setTimeout if you don't want it to be instantaneous.
Fiddle: https://jsfiddle.net/z6h9d028/5/
Inside the onkeyup, you can also call $('#contact_me').valid(), which will revalidate the whole form, although that may not be your desired outcome.
Edit: Sparky also helpfully mentioned that jquery-validate by default does allow keyup events, but it only does so after the first submit: jQuery validate plugin: validate on blur() by default
An alternative way would be to set the details of your validation as you currently are, without the onkeyup function, then set your own listeners and run $(element).valid():
$('#contact_me').validate({
rules: {
// ...
}
});
$('input').on('focus focusout keyup', function () {
$(this).valid();
});
Edit regarding your other issues:
Your errorPlacement function is doing some funky things. How it decides what is the next sibling or not seems to be working incorrectly. Also, you're adding the error HTML divs into your DOM manually, but they are actually generated by the plugin. So really, you're creating both, then trying to show them, kinda over-riding the plugin, kinda not, and the whole thing is going into a frenzy.
The solution is, I reckon, to remove those error divs, remove that errorPlacement function, and then modify the CSS selectors to get any id ending with "-error", which is what the plugin generates. So [id$='-error'] instead of .error_message
https://jsfiddle.net/z6h9d028/8/
Related
I want to do live form validation using javascript like if I type number in text field it should give error message instantly or vice versa.How can I achieve this.
You need to start by detecting changes in the input entries. You can do that easily by using the oninput event (read more here).
Looking at that example:
<script>
window.addEventListener('input', function (e) {
console.log("input event detected! coming from this element:", e.target);
}, false);
</script>
<input placeholder="type here and see console.">
Each time your input value changes, an event will be fired an received in that listener.
In your case, you need to add an event listener for each of the inputs and, instead of doing a console.log in the handler function, just call a generic function that will validate all the values for all the inputs in the form.
For the validations, you can look at multiple libraries, like validate.js or jQuery Validation. Also, take a look at validator.js.
I have a form that uses jQuery validation, using unobtrusive validation to declare rules. Currently I'm using the default submit behaviour where there is no validation on blur until the form is submitted (validating every field in the form), after which subsequent blurs validate just the blurred field.
I'd like to change this behaviour so that after a submit, blurring a single field revalidates the entire form, so that the error summary remains on screen until every issue has been addressed. The behaviour before submit should remain the same.
I've tried the following onfocusout methods based on other SO answers, with no luck:
onfocusout: function(element, event) {
$(element).valid();
}
and
onfocusout: function(element, event) {
this.element(element);
}
Both this.element(element) and $(element).valid() are for triggering validation on a single element. In your case, since you're trying to apply this inside of the options of the .validate() or .setDefaults() methods, you cannot use .valid() as it could potentially trigger an infinite recursion.
That leaves .element(). However, as per the docs, you can only use this on a single field, not the entire form.
How to validate the entire form on field blur instead of just the blurred field
I'd like to change this behaviour ... blurring a single field revalidates the entire form
The solution would be to write an external blur event handler attached to all relevant input elements and trigger the .valid() method attached to your form. Edit the selectors in this generic example for whatever is applicable to your particular form.
$('#myform input[type="text"]').on('blur', function() {
$('#myform').valid(); // <- trigger validation on entire form
});
$('#myform input[type="text"]') selects all text inputs within #myform
$('#myform') selects theformbased onid="myform"`
Problem with browsers Auto suggestions.
For example prefilling the user's address based on earlier user input...
Some conditions
autocomplete="on".
i am using "jQuery Validation Plugin 1.11.1".
I am filling the wrong data and click the submit, form validations trigger
next i filled date with browsers Auto suggestions this case form
validations not trigger. Any buddy know update the solution. [Fiddle][1].
First click the submit button next enter the values you observe.
next time click auto suggestion or auto complete -> error message still exit up to focus out...
[2]: http://jsfiddle.net/thiru715/57oyLjzh/2/
` `
[1]: http://i.stack.imgur.com/PDJv8.png
The validation for each field happens when you get out of that field (blur) and on other events (keyup, form submit...)
You'd have to hack it to work, for example, customize your jQuery code so that whenever you leave any field (and thus autocompletation can have happened) the validation is trigerred for all the fields.
See this to learn how to manually trigger the validation.
You can also try to do it using the change event. I'm not sure if it will work.
Please, add this to your fiddle and test it:
$("#registerform input").change(function() {
$(this).valid();
});
I'm not able to test it, because I cannot trigger the autocomplete.
If it doesn't work, try this:
$("#registerform input").blur(function() {
$("#registerform input").valid();
});
I would like to change the first letter of a word to uppercase. So, I have written some code on keyup() function.
Whenever I type inside the text filed, Word's first letter is getting changed to uppercase.
I also use autocomplete() function. The problem is, Whenever I choose a word from autocomplete drop down it's first letter is not getting changed to uppercase and also the last text box is getting auto focused.
FYI: I am triggering the keyup() function after the autocomplete selection.
jsfiddle: http://jsfiddle.net/8ke04mgs/5/
You can use change event on your textbox
$(document).on('change', 'inputBox', function() {
// Does some stuff and logs the event to the console
});
This will solve the autocomplete problem
Your current way of doing things would work perfectly if the select method you provide to the autocomplete library was called after value of the box was updated.
But it is not, it's called before and so the value that it capitalises is the old value and is immediately replaced by autocomplete anyway.
As #Alok has pointed out, you can use the 'change' event to wait a little longer.
To avoid writing out your event handler out twice, remember .on() can take multiple events, so I'd just call it on keyup and change like so
$('#element').on('keyup change', function() {
...
});
But I think in modern browsers 'change' should be enough.
TL;DR how can I get this self-explanatory JSFiddle to work?
From the W3C:
The blur event occurs when an element loses focus either via the pointing device or by tabbing navigation. This event is valid for the following elements: LABEL, INPUT, SELECT, TEXTAREA, and BUTTON.
The basic idea, HTML:
<form>
<label>
<input type="text" />
after focusing in input, there should be no blur when clicking here
</label>
</form>
but blur should fire when clicking here
And JS:
$("form, label").on("blur", function() {
alert("you're not going to see this");
});
It doesn't work. A more illustrative example is in this JSFiddle.
I also tried focusout, with this JSFiddle, but (presumably because it bubbles up from the input), it always fires.
I could probably rig up what I need with a hack like this: https://stackoverflow.com/a/5049387/458614 but I'd rather not have to.
Edit: There are lots of related questions and I have read all that I could find, none of which help. Some talk about setting tabindex=0 on the form or label elements. I have tried this in various permutations but it doesn't help. JSFiddle here. If you put it on the form, blur events do fire when you click outside the form. However, it doesn't apply to any of it's children: it won't pick up anything if you click on the input and then outside the form.
Edit 2: I don't really understand some of the answers posted so far and none seem to really... work. Anyway, to clarify, here is what I am trying to accomplish:
In my app, you can add tags to documents. When you click the "add tag" button, a previously-hidden text input field pops up and is focused. And then...
Clicking outside (on blur) should close the text input field again
Pressing enter should add the tag and close the input field
Clicking the "add tag" button should also add the tag and close the input field
The problem is that #1 and #3 are incompatible. The "add tag" button needs to perform a different action based on whether the text field is open or closed, but because I can only achieve #1 with an onblur event on the text field, the text field is closed by the time any action happens on the "add tag" button for #3.
Here is a JSFiddle with my best attempt so far.
The thing I think you are looking for is
e.stopPropagation();
This Fiddle here shows a little different way to handle it ... it put the hide on a window click (which would blur the input anyways) except on the label, which it would allow the click event to stop inside the label.
Happy coding!
use the below code to achieve the desired
$(document).on("blur", "label",function() {
$("div").append("form or label blurred<br>");
});
Here is the demo Fiddle
Try this it should work
.focus {
border-color:red;
}
$(document).ready(function() {
$('input').blur(function(){
$('input').removeClass("focus");
})
.focus(function() {
$(this).addClass("focus")
});
});
Add this piece of js in your Fiddle. you added listener for label but blur happens on anchor tag.
$("form a").on("blur", function() {
$("div").append("form or label blurred<br>");
});
according to your explanation i have create a demo
$("form > label >a").on("blur", function() {
return false
});
$("#outsideform > a").on("blur", function() {
alert("but blur should fire when clicking here");
});
Check the Demo here
For a while, I am posting an intermediate development. But this definitely will help you where exactly you should look for. The jquery implementation but not your javascript.
This is the real concern.
I have added 3 lines at different places. no big changes.
Added an || $("input").css("visibility") == "visible" to the if
condition
Added $("input").css("visibility","hidden"); to the inner else condition
$("input").css("visibility","visible"); to the outer (and last) else condition.
Please note this is intermediate, you need to click twice after a submit of non-empty text.
If I get time, I would post the correct working thing.
This is the fiddle.
tobek, your JSFiddle with my best attempt so far is almost there. The problem is your selector at the bottom in this section of code:
$("input").on("blur", function(){
$("input").hide();
});
You stated the problem correctly in your comments when you said: "THE PROBLEM: we never get in here because it's already been hidden because the input blurred".
Change the above section to this and I think you'll have what you're looking for.
$("input-blur label").on("blur", function(){
$("input").hide();
});
Because the "Add tag" link is inside the label clicking it doesn't trigger your "blur" function.