Keeping browser HTML form validation when submitting with javascript? - javascript

Is it possible to keep the default HTML validation if submitting via Javascript?
What I mean is that, if I submit a form using this JS method:
document.getElementById("mc-embedded-subscribe-form").submit();
How do I keep the defualt error messages thrown by the browser?
One workaround I thought of is using this:
<form onSubmit="return somefunction()">
But because the API returns the success inside a closure function, I can't use this method.

HTML5 has also specified a JS API that you can use to interact with forms/elements in regard to their validation status: https://www.w3.org/TR/html5/forms.html#the-constraint-validation-api
So the easiest way to achieve this would be to call the checkValidity method of your form, and only submit it when this returns true.
Something like this:
function submitIfValid() {
var form = document.getElementById("mc-embedded-subscribe-form");
if(form.checkValidity()) {
form.submit();
}
else {
//
}
}
and then you would just call that function when you want to trigger form submission.

according to my understanding of your question, html validation is not enough to halt submission, you have to validate required inputs in javascript too before submitting.
e.g
if (!empty(username)) {
document.getElementById("mc-embedded-subscribe-form").submit();
}

You do not need to use form.submit() ever. Do it properly (onsubmit), or use click() on the submit button.
Doing it properly...
I can't think of a good reason to automatically submit a visible form. To submit data without user-interaction use XMLHttpRequest or WebSockets.
A form is submitted by user interaction (e.g. pressing its submit button), so there is no need to use JavaScript to submit a form. It is more likely that you need JavaScript to prevent a form submission, by returning false in the onsubmit event handler.
...or use click()
To programatically invoke HTML5 validation (and also any JavaScript onsubmit event handlers attached to the form), you can call the click() function of a submit button that belongs to the form.
If the form has no submit button, you can create a temporary one:
var form = document.getElementById("mc-embedded-subscribe-form");
var button = document.createElement('input');
button.type = 'submit';
button.style.display = 'none';
form.appendChild(button);
button.click();
Forms with multiple submit buttons should each have name attributes so the server can detect which button the user clicked. You can 'click' these buttons using form.buttonName.click().

form attribute
this solution avoids javascript, let's say that #my-btn is a button outside the form #mc-embedded-subscribe-form, you could just set on it
<button id="my-btn" type="submit" form="mc-embedded-subscribe-form">Go!</button>
requestSubmit()
with vanilla javascript you could call requestSubmit()
const form = document.getElementById('mc-embedded-subscribe-form');
form.requestSubmit();
the hackish solution
you could put an hidden submit button in the form and then trigger the click event on it
<form id="mc-embedded-subscribe-form">
<button id="real-btn" type="submit" style="visibility: hidden"></button>
</form>
<button id="my-btn">Go!</button>
const btn = document.getElementById('my-btn');
const btn_real = document.getElementById('real-btn');
btn.addEventListener('click', (e) => {
e.preventDefault();
btn_real.click();
});

Related

How to make work on submit function in Javascript?

Ayo,
I'm a bit struggling with functions in JS.
The idea is that after the user clicks submit button, it checks if all the required fields have been filled out and if yes, it will trigger the loading animation.
The loading animation is supposed to be a status indicator in the meanwhile of sending the form and redirection to the success page.
I tried to use the onsubmit function in the form HTML tag but that does not work. The important thing is that it will happen one if the required fields are filled out.
Thanks
JS
const submit_btn = document.querySelector('.submit-btn')
function loading() {
this.innerHTML = "<div class='loader'></div>"
}
HTML
<form
onsubmit="loading()"
action="https://formsubmit.co/2007080c2cf8bd2ebb68506e7aa98c5f"
method="POST"
enctype="multipart/form-data"
>
I tried to use the onsubmit function in the form HTML tag but that does not work.
In regards to validation:
You can use the Constrained Validation API (see MDN) to check if all fields have been filled. Usually you want to use it after the user has submitted the <form> but before the form is sent to the server.
This is achievable by using it inside an event handler that is called on submitting the form.
In regards to event handling:
To implement the mechanism described above, what you want to do is adding an event listener to the submit event of the form via .addEventListener() instead of the onsubmit attribute. This way you'll receive an event object as argument of the event handler function with which you can prevent the form submission.
Example:
const myForm = document.querySelector('form'); // or '#myform', etc...
// define the event handler function
function onFormSubmission(event) {
const fields = Array.from(event.target.elements);
const allValid = fields.every(field => field.reportValidity());
if (!allValid) {
event.preventDefault(); // stop form submission
return;
}
event.target.innerHTML = '<div class="loading"></div>';
}
// add an event listener that fires on submission
myForm.addEventListener('submit', onFormSubmission);
<form id="myform" action="path/to/backend/script.php" method="POST" enctype="multipart/formdata" novalidate>
<input type="text" name="foo" placeholder="I am required!" required>
<hr>
<button type="submit">Submit form</button>
</form>
EDIT
Sorry, I missed to add the part that displays the loading information/element. Added (although you won't really see it because if all required fields are filled, the form will be submitted which results in a page refresh. You'd need something like XHR or similiar but that's not the scope of the question).

jQuery Validation with "formnovalidate" in submit button outside the <form>

I have an edit form using the jQuery Validation plugin. It's part of an ASP.NET Core project, also using ASP.NET's Unobtrusive Validation plugin. The form has two submit buttons, posting to different handlers server-side:
Submit changes
Delete entry
"Submit changes" is working fine, however I'd like the "Delete" button to skip any client-side validation. Currently it won't post the form if any required fields are missing (or any other validation condition doesn't pass).
I've tried the HTML5 formnovalidate attribute on the "Delete" button without success. Is there an equivalent feature in the jQuery Validation plugin? If not, how would you bypass validation only for a specific submit button?
EDIT:
The "Delete" button is actually outside the <form> tag, but referencing the form by ID through the form attribute:
<form id="my-form">
<!-- form fields and submit button here -->
</form>
<button type="submit" form="my-form" noformvalidate asp-page-handler="Delete">
Delete entry
</button>
I've found that when moving the "Delete" button inside the <form>, the noformvalidate attribute works as expected. I would really like to keep this button outside the <form> tag (due to the page's layout), though I might be able to work around it if there's no other way.
Any ideas on how to make it skip validation while placed outside the form?
The problem you have seems to be summarized in this issue:
Typical save vs submit button where save does not validate and submit
does. Save button is declared with the formnovalidate attrribute. Only
thing is that these buttons are outside of the form itself.
See, the plugin expects the submit buttons to be inside your form. It actually still handles both 'preventing' flags - cancel class and formnovalidate attribute - within click handler propagated from buttons to the top of the form (source):
// "this" is jQuery-wrapped HTMLFormElement with validator attaching
this.on( "click.validate", ":submit", function( event ) {
// Track the used submit button to properly handle scripted
// submits later.
validator.submitButton = event.currentTarget;
// Allow suppressing validation by adding a cancel class to the submit button
if ( $( this ).hasClass( "cancel" ) ) {
validator.cancelSubmit = true;
}
// Allow suppressing validation by adding the html5 formnovalidate attribute to the submit button
if ( $( this ).attr( "formnovalidate" ) !== undefined ) {
validator.cancelSubmit = true;
}
} );
... which clearly doesn't work if buttons are outside of form DOM hierarchy, like in your case. Only submit.validate handler is fired, but it expects to check validator.cancelSubmit flag (and set it to false if it's truthy).
One idea that comes to mind is to place your own click handler on Delete button that will override that flag. Validator instance is accessible through form $.data, as usually with jQuery plugins:
const validator = $.data(form, 'validator');
Perhaps you are looking for something like this:
var $frm = $('#my-form')
, frm = $frm[0]
, $btnsubmit = $('button[type="submit"]');
frm.addEventListener('submit', (evt) => {
var skipValidation = evt.submitter.hasAttribute('formnovalidate')
, validator = $frm.data('validator');
skipValidation && validator !== undefined
? (validator.cancelSubmit = true)
: ($frm.valid() && $btnsubmit.prop('disabled', true));
})
here I'm using a mix of vanilla JS and JQuery because not all submit-event properties are available in JQuery and is not so recommended to access JQuery data using vanilla JS.
In this case, there is no matter where are declared your submit-buttons but... you should be sure to execute the above script before $.validator.unobtrusive.parse(document) that mean before validator.unobtrusive become obtrusive.

javascript display :none function

Firstly apologies if this is not a very good question, but I am not very familiar with Javascript at all. Secondly I did do research to find my problem I refer you to this post
I wrote this very basic function
function hideBtn(){
var btn = document.getElementById("submitBtn").style.cssText="display:none";
}
echo'<input type="submit" value="submit" name="submit" id="submitBtn" class="buttono" onclick="hideBtn()" />';
Which I want to hide my submit button after form is clicked as currently it is still displaying
Any help very much welcomed
Can it be that when the form is submitted the page is refreshed, and thus the function was not actually triggered?
Can it be that when the form is submitted the page is refreshed, and thus the function was not actually triggered?
Yes, that's very likely to be the issue. If you don't want the page refreshed, don't use a submit button, or submit the form to another window, or use an submit event handler on the form element and prevent the default action.
Separately: It's best not to completely replace all of the styles on the element. Instead, just set the specific style you want:
var btn = document.getElementById("submitBtn").style.display = "none";
The style property on elements is an object with properties for each of the CSS styles.
Since you are using submit button, you need to stop form from submitting and refresh page.
Second thing, you are not using styles correctly to hide the button.
function hideBtn() {
var btn = document.getElementById("submitBtn").style.display="none";
return false; // Prevent form from submitting
}
You probably want to write:
var btn = document.getElementById("submitBtn").style.display = "none";
See more: http://www.w3schools.com/jsref/dom_obj_style.asp

How to prevent that a JQuery button submit my form?

I am absolutly new in JQuery development and I have the following problem.
I have a form that contains this JQuery button:
<!-- RESET BUTTON: -->
<td>
<button class="resetButton" name="submitReset" onclick="return resetSearch(); return false;">Reset</button>
</td>
Clicking this button the user reset to null two input that are into my form performing this JavaScript function:
function resetSearch() {
var f = document.getElementById('dataDaAForm');
f.dataDa.value = null;
f.dataA.value = null;
event.preventDefault();
}
The script is performed but the problem is that after that it go out from the previous function the form is submitted anyway and I don't want that this behavior happen.
How can I prevent that the form is submitted when the user click on the reset button? As you can see I also try to add this statment but it don't work:
event.preventDefault();
What am I missing? How can I fix this issue?
Another question is: is it the correct way to reset the values of the input tag of my form?
Give this a shot - you need to pass the event into the function. In addition, I've removed the need for inline JS.
$(".resetButton").click(function(e) {
var f = document.getElementById('dataDaAForm');
f.dataDa.value = null;
f.dataA.value = null;
e.preventDefault();
});
In addition to preventing the default, Javascript provides a method to reset your form:
$(".resetButton").click(function(e) {
document.getElementById("dataDaAForm").reset();
e.preventDefault();
});
Note: You tagged jquery, so I provided a jquery solution (although there is no jquery in your question).
The simplest way to create a reset button is an input type reset:
<input type="reset" value="Reset" />
Though if you really want to do it in javascript, the answer of James Hill will suffice
Try this
var form = $('#dataDaAForm')
$(".resetButton").on("click",function(e) {
form.reset()
e.preventDefault()
e.stopPropagation()
})

How to Prevent Users from Submitting a Form Twice

<input type="submit" name="btnADD" id="btnADD" value="ADD"/>
when user click add button twice, from get submitted twice with same data into table.
So Please help me to restrict user to submit from twice.
Once the form is submitted, attach a handler with jQuery that hijacks and "disables" the submit handler:
var $myForm = $("#my_form");
$myForm.submit(function(){
$myForm.submit(function(){
return false;
});
});
Returning "false" from the submit handler will prevent the form from submitting. Disabling buttons can have weird effects on how the form is handled. This approach seems to basically lack side effects and works even on forms that have multiple submit buttons.
try out this code..
<input type="submit" name="btnADD" id="btnADD" value="ADD" onclick="this.disabled=true;this.value='Sending, please wait...';this.form.submit();" />
You can disable the button after clicking or hide it.
<input type="submit" name="btnADD" id="btnADD" value="ADD" onclick="disableButton(this)"/>
js :
function disableButton(button) {
button.disabled = true;
button.value = "submitting...."
button.form.submit();
}
If you are working with java server side scripting and also using struts 2 then you refer this link which talks about on using token.
http://www.xinotes.org/notes/note/369/
A token should be generated and kept in session for the initial page render, when the request is submitted along with the token for the first time , in struts action run a thread with thread name as the token id and run the logic whatever the client has requested for , when client submit again the same request, check whether the thread is still running(thread.getcurrentthread().interrupted) if still running then send a client redirect 503.
And if you are not using any framework and looking for simple workout.
You can take help of the
java.util.UUID.randomUUID();
Just put the random uuid in session and also in hidden form field and at other side(the jsp page where you are handling other work like storing data into database etc.) take out the uuid from session and hidden form field, If form field matches than proceed further, remove uuid from session and if not than it might be possible that the form has been resubmitted.
For your help i am writing some code snippet to give idea about how to achieve the thing.
<%
String formId=(java.util.UUID.randomUUID()).toString();
session.setAttribute(formId,formId);
%>
<input type='hidden' id='formId' name='formId' value='<%=formId%>'>
You could notify the user that he drinks too much coffee but the best is to disabled the button with javascript, for example like so:
$("#btnADD").on('click', function(btn) {
btn.disabled = true;
});
I made a solution based on rogueleaderr's answer:
jQuery('form').submit(function(){
jQuery(this).unbind('submit'); // unbind this submit handler first and ...
jQuery(this).submit(function(){ // added the new submit handler (that does nothing)
return false;
});
console.log('submitting form'); // only for testing purposes
});
My solution for a similar issue was to create a separate, hidden, submit button. It works like so:
You click the first, visible button.
The first button is disabled.
The onclick causes the second submit button to be pressed.
The form is submitted.
<input type="submit" value="Email" onclick="this.disabled=true; this.value='Emailing...'; document.getElementById('submit-button').click();">
<input type="submit" id='submit-button' value="Email" name="btnSubmitSendCertificate" style='display:none;'>
I went this route just for clarity for others working on the code. There are other solutions that may be subjectively better.
You can use JavaScript.
Attach form.submit.disabled = true; to the onsubmit event of the form.
A savvy user can circumvent it, but it should prevent 99% of users from submitting twice.
You can display successful message using a pop up with OK button when click OK redirect to somewhere else
Disable the Submit Button
$('#btnADD').attr('disabled','disabled');
or
$('#btnADD').attr('disabled','true');
When user click on submit button disable that button.
<form onSubmit="disable()"></form>
function disable()
{
document.getElementById('submitBtn').disabled = true;
//SUBMIT HERE
}
Create a class for the form, in my case I used: _submitlock
$(document).ready(function () {
$(document).on('submit', '._submitlock', function (event) {
// Check if the form has already been submitted
if (!$(this).hasClass('_submitted')) {
// Mark the form as submitted
$(this).addClass('_submitted');
// Update the attributes of the submit buttons
$(this).find('[type="submit"]').attr('disabled', 'disabled');
// Add classes required to visually change the state of the button
$(this).find('[type="submit"]').addClass("buttoninactive");
$(this).find('[type="submit"]').removeClass("buttonactive");
} else {
// Prevent the submit from occurring.
event.preventDefault();
}
});});
Put a class on all your buttons type="submit" like for example "button-disable-onsubmit" and use jQuery script like the following:
$(function(){
$(".button-disable-onsubmit").click(function(){
$(this).attr("disabled", "disabled");
$(this).closest("form").submit();
});
});
Remember to keep this code on a generic javascript file so you can use it in many pages. Like this, it becomes an elegant and easy-to-reuse solution.
Additionally you can even add another line to change the text value as well:
$(this).val("Sending, please wait.");
Add a class to the form when submitted, stopping a user double clicking/submitting
$('form[method=post]').each(function(){
$(this).submit(function(form_submission) {
if($(form_submission.target).attr('data-submitted')){
form_submission.preventDefault();
}else{
$(form_submission.target).attr('data-submitted', true);
}
});
});
You can add a class to your form and your submit button and use jquery:
$(function() {
// prevent the submit button to be pressed twice
$(".createForm").submit(function() {
$(this).find('.submit').attr('disabled', true);
$(this).find('.submit').text('Sending, please wait...');
});
})
None of these solutions worked for me as my form is a chat and repeated submits are also required. However I'm surprised this simple solution wasn't offered here which will work in all cases.
var sending = 0;
$('#myForm').submit(function(){
if (sending == 0){
sending++;
// SUBMIT FORM
}else{
return false;
}
setTimeout(function(){sending = 0;},1000); //RESET SENDING TO 0 AFTER ONE SECOND
}
This only allows one submit in any one second interval.

Categories

Resources