Display native validation message in JavaScript - javascript

I'm currently developing a form which will be powered by HTML5 features and jQuery. One of the things I've been tasked with is ensuring that the native "Please fill in this field" message is still available to browsers which natively support validation.
My setup looks like so:
|----------|
| FORM |
|----------|
===BUTTON===
The form has several parts to it, and so the button is global across them all. The form then slides to the next section if complete.
Here is what I have now, this correctly fires the button event to the form and triggers a submit event.
$(".next").click(function() {
var $incoming = $(".nextPart #" + (currentSlide));
var incomingID = $incoming.data("cardid");
var partCode = "form-" + incomingID;
$("form[name='" + partCode + "']").trigger("submit");
});
$("form").bind('submit', function(event) {
var goForth = true;
if(!event.currentTarget.checkValidity()) goForth = false;
if(!goForth) return false;
/* Do some stuff with progress bar and more things */
return true;
});
However, even though the form submit fails, there is no validation message. Is there a way to pragmatically fire this on an element, or have I done something stupid?
For clarification, this is a screenshot of the validation message I am on about.

instead of event.currentTarget.checkValidity -- do this...
function checkValidity(elem) {
// check validity here
// retun true/false
}
and then in your submit handler do this...
if(checkValidity(event.currentTarget)) { ...
Also, it is generally NOT a good idea to trigger native browser events -- trigger is good for custom events -- if you need to submit the form you can call the submit() method of the form object like this..
$("form[name='" + partCode + "']").get(0).submit();

As I described in my first post, I was using a click event on a button which was in a global scope. This was then sending a submit action to the form which, although was sending the form to be submitted, it wasn't firing the bubble event (whatever the hell that is) on the elements.
To fix this, I wrapped all of my slides in one form instead of multiples. I kept my submit button outside of the slides, so it still acted as a global navigation item.
Removing the click event from this button and changing the type of it to submit now gets the bubble displaying.
Not the best fix, since the bubble should be able to be trigged without having to submit the form, however, I guess with HTML5 validation, you can define the parameters for what is accepted and what isn't.

Related

Submit event listener for an AJAX form

I am unable to get an event listener to fire on forms that use AJAX. I don't have control over the inline structure of these forms.
Ultimately, I want to disable the form submit, but for development, a simple message to the console would be great. Disabling the form submit is explained well in this question : Submit Event Listener for a form, and on my non-AJAX forms, works perfectly.
Since I can't control the inline structure of the forms, I loop through all forms and assign an event listener to each.
var vForms = document.querySelectorAll('form');
for(i=0; i<vForms.length; i++){
vForms[i].addEventListener('submit', event => {
console.log('FORM SUBMITTED : ' + event);
});
}
I've also tried .onSubmit
vForms[i].onsubmit = function(e){
console.log('FORM SUBMITTED : ' + e);
};
Using either approach, no errors show during the loop that indicates the .addEventListener or .onSubmit didn't work.
I've tried putting the loop after a long delay, just to see if they were loading after the code first ran, but a delay far longer than the load time didn't help.
I also tried disabling the AJAX loading, to ensure that is really the problem, and it worked after doing so and didn't after re-enabling it.
Thank you in advance for any help you may provide.

HTML 5 form submit handler called even if form is invalid

I'm writing some unit tests for an HTML 5 app that uses the HTML 5 form validation API. I've attached a submit event handler to the form that does some custom handling before serializing to JSON and passing it off to my server.
What I've discovered, though, is that if I initiate a jQuery submit() event on the form, even if it's invalid, my submit handler still gets called.
Instead, I'd expect my event handler not to have been called because the form is invalid.
I've created a JSFiddle to demonstrate (tested in Chrome 20):
http://jsfiddle.net/jonbca/SYg4h/22/
So, what gives?
Triggering the ".submit()" handler simply does not have anything to do with the HTML5 form validation mechanism. That mechanism is really quite independent of JavaScript, and in fact it's mostly unavailable from the DOM API. You can explicitly call "checkValidity()" on a form element, but that just returns a boolean result and does not do any of the visual form updates that happen when the user clicks a "submit" form control.
It's important to keep in mind that many of the fancy HTML5 "smart markup" behaviors are designed to allow things to happen without the need for JavaScript.
Try triggering the submit button:
$('#submitBtn').click();
If you don't have one, just do a hidden one, that replicates the action.
Fiddle: http://jsfiddle.net/SYg4h/30/
Try using a click handler on the button
$('#myform').submit(function (e) {
// check for validation here
var value = $('#foo').val();
if (!value || value == undefined)
$('#message').html('It did not submit');
else
$('#message').html("It submitted");
return false;
});
$('#submitBtn').click(function(){
$('#myform').submit();
});
Try this: http://jsfiddle.net/Cqzcu/4/

jQuery validation errors are not shown when I'm not using a submit button

Check out this jsbin.
I have a form with a custom button that submits it via ajax (not a real submit button).
I'm using jquery-validation to validate the form, and running validate().checkForm() to validate it.
My question is - why don't the error messages on the specific fields appear when I do this? They appear all right when I'm using a standard submit button.
Edit: My example doesn't include the ajax submission, but just pretend it's there.
Because validate is listening for the submit event.
If you add $("form").submit(); inside the click event then it is fired.
http://jsbin.com/avuhed/edit#javascript,html,live
Piggy-backing on what #weezer said, you'll need to associate the form submission event with the button click, and you'll also want to put it inside the form itself. Right now it's sitting outside of it. For future updates, and sanity, it'll make your life easier to keep it grouped together.
The jquery validation is triggered by a standard form submit.
You may need to attach a .click handler to your custom submit button as so:
var isValid = $("#yourForm").valid();
if(isValid) {
// Do stuff
}
Yes, i have and if you put:
$("#submit").click(function() {
var isValid = $("#form").isValid();
if(isValid) {
alert('test');
}
});
Instead of what you have and move the custom button within the form, the validation works. http://jsbin.com/ajeyot/9

jQuery selector "memory"

I have a form with multiple fields, and each time the user changes a field the form is submitted (via hidden iframe), and the response is placed within an appropriate div on the page via a callback. The first time this works fine. But on each subsequent field change and submission, the response is shown in every div that has been filled with a response (so they all show the same thing, not the desired behavior).
Can anyone tell me why this is happening? It seems that there is some retention of the selectors that have been called before (since last page load)... but I'm not sure. Here's my code:
$(function ()
{
$('#ImageAddForm input').change(function (){
form = $('#ImageAddForm');
var fldDiv = $(this).parent().attr('id'); // eg Image11
var thDiv = fldDiv.replace('Image', 'Thumb'); // eg Thumb11
$(form).iframePostForm({
post : function (){
var msg = 'Uploading file...';
$("#" + thDiv).html(msg);
},
complete : function (response){
$("#" + thDiv).html(response);
$(':input', '#ImageAddForm').not(':hidden').val('');
}
});
form.submit();
});
});
I'm not familiar with that plug-in, but I have a suspicion about what might be causing your problem. You are attaching some functionality to your form with the plug-in inside of your change event. This means that on every change you are attaching again, which is likely to cause some problems. Two solutions suggest themselves:
1) If the plug-in has some kind of call to unbind or destroy itself, call that right before binding the plug-in to the form. This should prevent any weird behavior caused by multiple binding.
2) Better solution: bind the plug-in to the form outside your change event, and scope your variables (fldDiv, tdDiv) such that they will be accessible to both your change event (so that they can be modified based on what changed) and the functions used by the plug-in (for post and complete). This way you will only bind the plug-in once, but can still pass and receive different data based on what field changed.

Can I determine what button was clicked to fire an onSubmit event?

I've got an onsubmit handler added to a form like so:
$('#content_form').bind('submit',function(e) {
source = $(e.target).attr('name');
alert(source);
return false;
});
so e.target = the form element. I'm using several submit buttons, and need to determine which one was actually clicked (in modern browsers, that clicked button is the only one that submits, I'm doing this for IE6 compat - it submits the values of all the buttons).
My only thought it to kill any onsubmit events, and then tie click events to the buttons themselves. This would kill the form functionality entirely if javascript wasn't enabled, so I'd like to avoid this.
An easy (but possibly naive) implementation would be to have the onclick handler for each button set a field indicating which one was the last one clicked. In your submit handler, you could then check the value of this field.
$('#content_form input:submit').bind('click', function(e) {
$('#content_form').submit();
// you can now reference this or $(this),
// which should contain a reference to your button
});
Have you checked out the jQuery Form Plugin? It handles submitting forms via ajax very nicely and will handle this problem (along with many others) for you.
Something else you could do is use preventDefault(); instead of return false

Categories

Resources