Manually invoke HTML5 form validation - html

I have a legacy form that I'm trying to update to do simple HTML5 form validation.
Currently, it uses reCaptcha, and invokes a verify() function that validates the reCaptcha challenge before forwarding the contents of the form. I would like to ensure that the form passes HTML5 validation before continuing with the reCaptcha processing, and display the appropriate error messages that the browser would use by default.
The iframe containing the form as the <!DOCTYPE html> doctype. The input fields have the required attribute.
The submit button has the following:
<input type="button" id="script_send" onclick="javascript:verify(this.form);" value="ENVIAR">
The verify script has the basic structure.
function verify(theForm) {
form = theForm;
/* Recaptcha processing */
}
I tried using
if (!form.checkValidity()) {
return false;
}
and even though the form was not submitted, I get no errors displayed on the screen, showing the user what fields they should be providing.
I have seen this jsfiddle [http://jsfiddle.net/5ycZz/] used to demonstrate the checkValidity() function, but even that does not display the visual error cues that I would expect to see, in Chrome, IE10 or FF.

Try setting the submit event on the form instead of putting a click action on the submit button. The submit event fires AFTER validation so it should only happen if all other constraints passed. This also means you wont have to call form.checkValidity() in your verify function.
<form onsubmit="verify(this)">
...
</form>

This solving trouble:
if (!form.checkValidity()) {
form.reportValidity();
return false;
}

Related

Wait for form response after submitting with button.click()

I am using Puppeteer to submit a form and I can't figure out how to wait for the response because the normal approaches don't work.
Submitting must be done by invoking click() on the submit button rather than calling form.submit() which on this webpage results in an error that I can't control. Therefore, this does not work:
await page.$eval('#form', form => form.submit);
Submitting the form does not navigate to a new page, but rather modifies the HTML in place. I have also tried waitForNavigation with every waitUntil option, none works.
Are there any other approaches I can try? Thanks
Submitting the form does not navigate to a new page, but rather modifies the HTML in place.
In this case you can wait for a css selector via page.waitForSelector
For example if a success message is shown above your form after a successful submit, just wait for this css selector to appear in the dom:
await page.waitForSelector('form div.success');

How to Prevent JEditable Form Submission with Webkit browsers

Using the JEditable JQuery plugin, and everything seemed to work fine in Firefox. However, in Chrome whenever I selected something out of a JEditable dropdown, or clicked Enter when editing a JEditable textbox, the form JEditable creates on the fly was being submitted, and my entire page was refreshing. I didn't want that to happen, as I've got it configured to call a custom function that makes an Ajax call to do the update. How do you keep the JEditable form from being submitted when changing the value of one of the form inputs?
My understanding from researching online is this is a Webkit-browser issue, not just a Chrome issue, as it seems Webkit-based browsers automatically submit forms when inputs in the form are changed.
After much trial-and-error I found one way to get around this is to use JEditable's bind function. The bind function gives you access to the form JEditable creates, and you can hijack the onsubmit event with that.
So first, create a function to override the form's onsubmit event.
var bindSubmitDisableWebkitSubmission = function(settings, self){
$('form', self).attr("onsubmit", "return false;");
}
Then bind that function to the various JEditable events that you don't want to submit the form.
$.editable.types['select'].plugin = bindSubmitDisableWebkitSubmission;
Note that using preventDefault and returning false (see below) didn't work.
function bindSubmitDisableWebkitSubmission (settings, self) {
$('form', self).submit(function(e){
e.preventDefault();
return false;
});
}

Clear all fields in a form upon going back with browser back button

I need a way to clear all the fields within a form when a user uses the browser back button. Right now, the browser remembers all the last values and displays them when you go back.
More clarification on why I need this
I've a disabled input field whose value is auto-generated using an algorithm to make it unique within a certain group of data. Once I've submitted the form and data is entered into the database, user should not be able to use the same value again to submit the same form. Hence I've disabled the input field in the first place. But if the user uses the browser back button, the browser remembers the last value and the same value is retained in the input field. Hence the user can submit the form with the same value again.
What I don't understand is what exactly happens when you press the browser back button. It seem like the entire page is retrieved from cache without ever contacting the server if the page size is within the browser cache limit. How do I ensure that the page is loaded from the server regardless of browser setting when you press the browser back button?
Another way without JavaScript is to use <form autocomplete="off"> to prevent the browser from re-filling the form with the last values.
See also this question
Tested this only with a single <input type="text"> inside the form, but works fine in current Chrome and Firefox, unfortunately not in IE10.
Modern browsers implement something known as back-forward cache (BFCache). When you hit back/forward button the actual page is not reloaded (and the scripts are never re-run).
If you have to do something in case of user hitting back/forward keys - listen for BFCache pageshow and pagehide events:
window.addEventListener("pageshow", () => {
// update hidden input field
});
See more details for Gecko and WebKit implementations.
I came across this post while searching for a way to clear the entire form related to the BFCache (back/forward button cache) in Chrome.
In addition to what Sim supplied, my use case required that the details needed to be combined with Clear Form on Back Button?.
I found that the best way to do this is in allow the form to behave as it expects, and to trigger an event:
$(window).bind("pageshow", function() {
var form = $('form');
// let the browser natively reset defaults
form[0].reset();
});
If you are not handling the input events to generate an object in JavaScript, or something else for that matter, then you are done. However, if you are listening to the events, then at least in Chrome you need to trigger a change event yourself (or whatever event you care to handle, including a custom one):
form.find(':input').not(':button,:submit,:reset,:hidden').trigger('change');
That must be added after the reset to do any good.
If you need to compatible with older browsers as well "pageshow" option might not work. Following code worked for me.
$(window).load(function() {
$('form').get(0).reset(); //clear form data on page load
});
This is what worked for me.
$(window).bind("pageshow", function() {
$("#id").val('');
$("#another_id").val('');
});
I initially had this in the $(document).ready section of my jquery, which also worked. However, I heard that not all browsers fire $(document).ready on hitting back button, so I took it out. I don't know the pros and cons of this approach, but I have tested on multiple browsers and on multiple devices, and no issues with this solution were found.
Because I have some complicated forms with some fields that are pre-fill by JS, clearing all fields is not suitable for me. So I found this solution, it detects the page was accessed by hitting the back/forward button and then does a page reload to get everything back to its original state. I think it will be useful to someone:
window.onpageshow = function(event) {
if (event.persisted || performance.getEntriesByType("navigation")[0].type === 'back_forward') {
location.reload();
}
};
As indicated in other answers setting autocomplete to "off" does the trick, but in php, what worked for me looks like this...
$form['select_state'] = array(
'#type' => 'select',
'#attributes' => array('autocomplete' =>'off'),
'#options' => $options_state,
'#default_value' => 'none');

Enter sending HTML form with no submit

I replaced the type="submit" on my form with a type="button", to prevent form submits when the user presses enter. Will this prevent enter from submitting the form in all browsers?
Some browsers will still automatically submit when enter is pressed. If you really need some feature apparented to this, you might rather implement your own filtering with the onSubmit event handler.
Then, you can force the submission of the form by actually calling the submit method from Javascript. Of course, you would need to set a specific flag to allow your submit to go through this time. Something along the lines of (with jQuery)
//flag definition
var form_is_ready = false;
//event handler for the form submission
$('#your-form-id').submit(function() {
if (!form_is_ready) {
return false;
}
});
//function you have to call to actually submit the form
function do_submit() {
form_is_ready = true;
$('#your-form-id').submit();
}
That's just a crack shot piece of code written on the fly. You should adapt it to suit your needs.
This is a poor decision for usability and should be avoided.
It's seems not. This question suggests that submission will still happen in Chrome.

Form Double Post Issue

I understand that double posts has been a problem with forms forever.
I am using the token server-side method to handle this issue, but I find that it doesn't seem to work flawlessly. I have the system set to create a unique token for every form, and then record that token in a SESSION after it has been posted.
The SESSION is actually an array of every form the user has ever posted (to be reset when the SESSION expires), and on each submit the system checks in_array() to see if that form has ever already been posted... if so then it stops them.
Seems like in production the system cannot record the completed token into the SESSION quick enough to deal with double clicks on the submit button. So revisiting an old page is handled fine, but the immediate double click of the submit creates a problem.
Not sure what I can do to fix this issue.
How about disabling the submit button immediately upon clicking (via Javascript, with an onClick handler)? This obviously won't fix all issues, but it might cover the cases where the system isn't quick enough to record the token into SESSION.
I have had this issue as well with something internal for the company I am working for. In my experience people click multiple times because they don't think anything is happening. What I have done is to remove the ability to submit the form and display some sort of message saying that the information is being processed.
Pop-up divs and just disabling the button work well.
I had same problem and I resolve with jQuery.
I added class singleClick in submit button there I would like to have single click and also added some javascript code
<input type="submit" class="singleClick" value="Send Request">
$(function () {
$('.singleClick').on('click', function () {
$(this).attr('disabled', true);
});
});