Show form default Validation Status Programmatically - javascript

I want to submit a form using ajax. So I am not using the type=submit. I am using a onClick event on a link(<a>) to send the form data using ajax. I also want to take advantage of HTML5 form validation capabilities.
So before sending the data, I used the function .checkValidity to check the validity of the form.
If it returns true then I send the data. But when it return false I want to show user that the form is invalid using HTML5 default notifying scheme. But I don't know how to trigger that.
Is there is any way to show the validation of the form programmatically.
One way to do is trigger the submit event if checkValidity return false. But this will refresh the page. I don't want to change the state of the page.
checkValidity only checks validity and inform the program. It doesn't inform the user interactively.

We have exactly the same problem and we tried very different things and a lot of them were hacks like pseudo submits and event.preventDefault() approaches. All in all i must say that HTML5 validation is nice in general but really bad in practice because its not possible to display backend validation errors the same way as frontend validation errors.
And only god knows why the HTML5 folks didnt thought about a simple API where we can trigger the validation like this element.triggerValidationMessage('my message');

You can do it if you let your form have a submit button and return false!
And you cán do it in the same event handler as the non-submits!
So, first test if you are part of a form and if so, make it check Validity and never return true (even if valid)!
$('.ajx')
.on("submit click", function(e) {
var $this = $(this)
//Force native form validating and notification
form = $this.closest('form')[0]
if (form) {
//Follow through with form submit (element must be of submit type!)
if(!form.checkValidity()) {
//don't ask me!
sleep(3000);
return false
}
}
//only preventDEfault AFTER possible form element click
e.preventDefault()
//...your project further ajax code
//Makes sure your form never submits
if (e.type=='submit') return false
}
Small downside: You have to do this on the submit button, but it's always possible to change your <a> into type=submit. You don't have to change the non form <a>'s though!

Related

onSubmit wont fire when using enter key

My question is about react, onSubmit and preventDefault.
I've got a form, which handles between 2 - 4 steps of user input depending on certain cases.
<Form>
{StepRendersHere}
</Form>
The form has a onSubmit event that prevents default (and stopPropagation).
When using the button for "next step" the event fires, and the form is NOT submitted.
But when using the enter key, the event is fired, but the form is posted. This results in the site refreshing with the form data as url parameters.
The weird thing is that if none of the buttons in the form has type="submit". The onSubmit doesn't even fire on enter key.
isDefaultPrevented returns true in both cases.
Any hints/thoughts on how I can prevent the form from posting when pressing enter? My issue is with Enter key posting the form, despite preventDefault.
Have tried binding the enter key to a event that prevents default, doesn't work. Might have done it the wrong way though.
UPDATE (implementation)
<Form onSubmit={this.inc_step} id="applicationform">
{FormStepRenderedHere}
</Form>
inc_step = e => {
e.preventDefault();
e.stopPropagation();
alert( e.isDefaultPrevented() )
let new_step = this.state.current_step + 1;
alert('INSIDE INC STEP');
if (this.validateForm()) {
this.setState({
current_step: new_step
})
}
}
UPDATE (FIXED IT)
I found a solution, and want to share if anyone else has the same problem.
My solution however might be unique to semantic ui, which i'm using. I solved it by putting as={Form.Group} on the form, mening it wont render as a form, with its standard events, such as enter key submit. Now the enter key does nothing, as I wanted it.
Thank you for the comments!
A much easier way to accomplish this is to add a button element to your form and add the display none css attribute (if you don't want to see the button).
The button automatically adds the ability to use the enter key with onSubmit.
I found a solution, and want to share if anyone else has the same problem.
My solution however might be unique to semantic ui, which i'm using. I solved it by putting as={Form.Group} on the form, mening it wont render as a form, with its standard events, such as enter key submit. Now the enter key does nothing, as I wanted it.
So actually not rendering the form as a form to begin with was the solution.

how to change the action of a form when the submit button is pressed || make the submit button clickable only once?

I was wondering if there was a way to make a submit button in html on clickable once, I am having an issue with users submitting multiple lines of information into a database because of impatience. I know this is the issue because I have tested it myself, the php written for the queries is solid, the problem is I have users that are impatient.
So my question is this, is there any code regardless of the language be it javascript, jquery, php or otherwise that I can use to either change the action of the form so that it can't be resubmitted over and over again, or to change the type of button of the submit button. I know that I can use javascript to change an element and its contents but is that really necessary or is there a simpler way?
thanks for all of your help.
Have you tried disabaling the button once clicked ? You Could Try something like this.
$("#SubmitButton").click(function(e){
e.preventDefault();
$(this).attr("disabled","disabled");
$("#TargitFormId").submit();
alert("Please wait while we save your information");
//Or you could use a nicer UI Here
});
You must use .submit() instead of .click. Beacuse user may use enter key for submit form. So you can use this code
var hadSent=false;
$("#FormId").submit(function(event){
if(hadSent==true){event.preventDefault()}
hadSent=true; // for prevent next submitions
})

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/

IE7 & IE8 does not trigger onsubmit javascript *before* submittion

I have a search form:
<form class="searchForm" id="topSearchForm" action="/search.ds">
that has an onsubmit-event attached to it, triggering a javascript. The purpose of this javascript is to empty certain form-fields before submission of the form based on certain criteria.
To be clear, what needs to happend is:
User input -> User clicks search button (or presses "enter") -> Javascript runs -> fields are cleared -> form is submitted
This works exactly as intended in all browsers except in IE7 and IE8. The javascript runs but for some reason the form submission is done before the fields are being cleared by the javascript. This causes the submitted page to include the data from fields that were supposed to be cleared.
I only have control of (certain parts of) the UI and cannot handle anything after the submission of the form. For usability purpose it is important that these fields (that should be cleared) are filled out up until the user submits the form.
Why is the internal logic different in IE7 & IE8 (it works fine in IE9 and "all other browsers)? Is there a way for me to circumvent this issue?
Here are some more code to clarify:
I attach the event to the form:
var formElement = document.getElementById("topSearchForm");
[...]
formElement.attachEvent('onsubmit', function() {clearForSubmit()});
and clearForSubmit is defined and is triggered.
You can try something like this in the js
<form onsubmit="clearForSubmit(); return false;">
this will NOT submit the form, you can submit the form after you clear it with
form_name.submit();
Use an onclick event instead of onsubmit, then submit the form at the end of the function in code.

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

Categories

Resources