In my HTML code I have required fields and regular expression pattern checking using HTML5 attributes. I want to submit my data to my server via AJAX but I have to use e.preventDefault();
Using that, disables all the HTML5 attributes like "required" and "type=email" and the built in HTML5 client side check. Basically the user can just submit an empty form.
Is there a way to make HTML5 first check if the attributes i specified are met, then e.preventDefault from submitting so i can manually submit via AJAX?
$("input[type='submit']#input_submit").click(
function(e) {
//Prevents form from submitting right away:
e.preventDefault();
// Allows or keeps halting form submission process; returns true or false.
validationForm();
});
function validationForm() {
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="lastname">
<p>Last Name</p>
<input type="text" name="lastname" placeholder="Last Name" pattern="[a-zA-Z]+" title="Letters Only" required></input>
</section>
<input id="input_submit" type="submit" value="submit">
If you instead prevent the form submit from happening (instead of the button click), you will get the behaviour you want.
$("form#your_form").on("submit", function(e) {
e.preventDefault();
alert();
});
https://jsfiddle.net/4o8nnkjy/
So in the above example, the alert only happens if the form is valid.
You can change the submit for a button instead.
<input id="button" type="button">
Then, when the user clicks button
$('#button').click(function(){validationForm(input1, input2, etc);});
So, what have to do validationForm function? All you want to do with validations.
function validationForm(input1, input2, input3){
//Make all your validations
//Then, if all is correct, send the data via AJAX
}
Related
I have a HTML form with some fields and a submit button. couple of fields are mandatory. I have a set of JavaScript code which i need to execute only if the form validation is successful. If there is some validation error on the form, the JavaScript code shall not execute. Below is the sample code:
<form id="sampleForm" method="post" action="">
<input type="text" id="firstname" required />
<input type="text" id="secondname" required />
<input type="submit" value="Submit" />
</form>
/*JavaScript*/
$("#sampleForm").submit(function(){
//Set of JavaScript code to execute if validation is success.
});
For me above JavaScript code does not work.
Please help!
In a comment you've said:
But if i use $("#sampleForm").submit() to submit the form, the form gets submitted but if i write function inside submit() ($("#sampleForm").submit(function(){ //Set of JavaScript code to execute if validation is success. });) then nothing happens !
That function is called when the submit event is fired, but the event isn't fire when the controls are invalid because the form won't be submitted.
The individual form controls get an invalid event when the user tries to submit the form when they're invalid. You can use that to provide feedback beyond what the browser supplies if you like:
$("#sampleform")
.on("submit", function() {
alert("Got the 'submit' event; form is being submitted");
})
.find("input, select")
.on("invalid", function() {
// Will fire for *EACH* invalid control
alert("Validation failed");;
});
Fiddle (Stack Snippets don't allow form submission even when it's cancelled.)
In case you need to submit the form programmatically (by calling submit), you can use checkValidity first to see if the form is valid:
// When submitting programmatically
var form = $("#sampleForm");
if (form[0].checkValidity()) {
form.submit();
}
Side note: When you use jQuery to submit the form (above), submit event handlers will be called. But if you use the DOM to submit the form ($("#sampleForm)[0].submit()), they won't be.
Just write a submit handler and execute your codes.
$("#sampleForm").submit(function(){
// Your code.
})
Submit handler triggers only when you complete the validation by HTML5 custom validator.
Here is a demo : http://jsfiddle.net/sureshatta/9ky8Z/118/
Html5 form have checkValidity method.Also since it is a form and button type is submit it will default throw an error pop up if it is not valid. checkValidity method return a boolean value true if it is valid. You can take a look in this method for further your job
$("#sampleForm").submit(function(e) {
var result = document.getElementById('firstname').checkValidity()
console.log(result) // will log true
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="sampleForm" method="post" action="">
<input type="text" id="firstname" required />
<input type="text" id="secondname" required />
<input type="submit" value="Submit" />
</form>
Thanks everyone for the answers!
I tried each one of your's solution which helped me to reach to my solution. Below worked for me:
if($("#sampleForm").valid()){
$("#sampleForm").submit();
//Set of JavaScript code to execute.
}
I have a HTML page containing a form. I want to make some fields "required". The problem is that I'm not using a <input type="submit"> in my form, instead, I use a Javascript function to submit the form because I need to send a Javascript variable to my server. Here is my code:
<form action="/toServer">
Username: <input type="text" name="usrname" required>
<input type="button" onclick="submitForm(this.form)" value="Submit">
</form>
var submitForm = function(frm){
var qstNbr = document.getElementById('hiddenField');
qstNbr.value = someJsVariable;
frm.submit();
}
So, Even is I have the required attribute in my input but the form is still being submitted even if I don't enter anything in the input.
Here is a JSFiddle of how I want my form to behave when clicking on the button without entering anything.
Anyone knows how form.submit() is different from having an <input> of type="submit" ?
EDIT: After following user2696779's answer and doing a little modification, here's the final working code:
<form action="/toServer">
Username: <input type="text" name="usrname" required>
<input type="submit" onclick="submitForm(this.form)" value="Submit">
</form>
var submitForm = function(frm){
if (frm.checkValidity()) {
var qstNbr = document.getElementById('hiddenField');
qstNbr.value = someJsVariable;
frm.submit();
}
}
Your current HTML input button isn't a submit type, it's a button type. The requred attribute on your input element is therefore ignored. To change this, change your button's type to submit:
<input type="submit" value="Submit">
Browsers which support the required attribute will now display a warning when the button is clicked:
JSFiddle demo.
Submitting using javascript will not trigger any validation. If you want to submit using a regular button + javascript and still have validation, you may use HTML5's checkValidity function to verify form fields, or the entire form.
For example, using JQuery:
if(!$('form')[0].checkValidity()) {
alert('not valid');
}
else {
$('form').submit();
}
See fiddle for working example: http://jsfiddle.net/8Kmck/2/
I have the following HTML form, which allows a user to optionally save a custom label for their product.
<form action="http://domain.com/members/systems" method="post" class="mod-SystemLabel-EditForm">
<label class="mod-SystemLabel-EditLabel" for="label-623">Customer label</label>
<input type="text" value="sdff sdf sd" name="fields[customer-label]" class="mod-SystemLabel-EditInput" id="label-623">
Clear
Cancel
<input type="submit" value="Save" name="action[system-edit-label]">
<input type="hidden" value="623" name="id">
</form>
If I manually clear my text input and submit my form, Symphony CMS records the empty value as expected.
If I use jQuery to trigger the form submission as below, Symphony CMS leaves (or re-saves?) the current value as it was.
$('.mod-SystemLabel-OtherButton-clear').click(function(e) {
e.preventDefault();
$(this).siblings('.mod-SystemLabel-EditInput').val('');
//alert($(this).closest('form').serialize());
$(this).closest('form').submit();
});
If I uncomment the commented line, the alert contains:
fields%5Bcustomer-label%5D=&id=623
This serialization is the same as what is produced when I backspace the input myself, so it looks like the actual form submission should be the same as a manual input clearing and click of the submit button.
The Symphony field is not set to be required and does not have any validation rules.
Why is the end result different and how can I get the empty value to be saved, overwriting the previous product label?
The form’s submit input’s name is not passed when the form is submitted via JavaScript, and Symphony CMS uses this to trigger the appropriate event.
To get the event name passed along with the submit input, trigger a “click”.
$('.mod-SystemLabel-OtherButton-clear').click(function(e) {
e.preventDefault();
$(this).siblings('.mod-SystemLabel-EditInput').val('');
$(this).siblings('input[type=submit]').trigger('click');
});
I have a form that has two submit buttons. I want to submit the form manually using JavaScript and have the input button used to submit the form posted along with the other form elements, as it would be if the form was submitted automatically. There's quite a lot of chatter on this subject, but I can't find an answer.
<form method="post" action="echoToScreenAndLog.jsp" id="form1">
<input id="field1" name="field1"/>
<input type="text" size="20" id="field2" name="field2"/>
<input type="submit" value="Do One" name="sub1_name" id="sub1_id"/>
<input type="submit" value="Do Two" name="sub2_name" id="sub2_id"/>
</form>
When the form is submitted above using the "Do One" button, the posted parameters are field1="xxx", field2="yyy", sub1_name="Do One".
But I want to submit the form manually...
<form method="post" action="echoToScreenAndLog.jsp" id="form1">
<input id="field1" name="field1"/>
<input type="text" size="20" id="field2" name="field2"/>
<input type="submit" value="Do One" name="sub1_name" id="sub1_id"/>
<input type="submit" value="Do Two" name="sub2_name" id="sub2_id"/>
</form>
<script type="text/javascript">
var btn = document.getElementById('sub1_id');
btn.onclick=function() {
return mySubmit(document.getElementById('form1'), ...);
}
</script>
but doing a manual submission of the form in the mySubmit function does not post the sub1_name parameter. I can understand that - I've bypassed the submission so the form is not being submitted using the buttons and therefore it makes no sense to post a parameter representing the button used to submit the form.
When I look at the elements of the form in the onclick handler, I can see both buttons. I'm not overly surprised by that either, they are elements on the form after all, but what I don't get is that if I add an element inside my onclick handler then the element I add IS posted and the two original submit buttons are not posted. Just to complete the picture, here's the code that adds the element:
<script type="text/javascript">
var btn = document.getElementById('sub1_id');
btn.onclick=function() {
var f = document.getElementById('form1');
var s = document.createElement("input");
s.type="hidden"; s.name="xsubmit_name"; s.value="Bob"; s.id="xsubmit_id";
f.appendChild(s);
// s gets posted
return mySubmit(f, ...);
}
</script>
Adding the input element could work for me, but I'm confused how the browser knows to post my added element and not the original two input elements.
Thank you.
The specification says that the first step for form submission is:
Step one: Identify the successful controls
"Successful controls" are defined as:
A successful control is "valid" for submission. Every successful control has its control name paired with its current value as part of the submitted form data set. A successful control must be defined within a FORM element and must have a control name.
However:
...
If a form contains more than one submit button, only the activated submit button is successful.
Since none of the submit buttons are activated, none are sent. Hidden input elements, on the other hand, are valid and will just be submitted along. Note that you add the hidden elements before calling mySubmit(), so at the time the above steps are executed (i.e. during submit), the hidden element is just another successful control part of the form, and thus sent.
may use
var btn = document.getElementById('sub1_id');
btn.onsubmit=function() {
return false;
}
btn.onclick=function() {
var f = document.getElementById('form1');
var s = document.createElement("input");
s.type="hidden"; s.name="xsubmit_name"; s.value="Bob"; s.id="xsubmit_id";
f.appendChild(s);
f.submit()
}
I have a form with multiple submit buttons and I'm listening for the 'submit' event via JavaScript. I want to know which submit button or form field (if the user pressed 'Enter/Return') triggered the submit event. Is there a way to get the HTML element that the user clicked on or pressed 'Enter/Return' in?
Update since people aren't understanding me:
This is via JavaScript before the form is submitted. No server-side detection allowed. I also need to handle the form being submitted via the user pressing Enter or Return.
Code
<form action="" method="POST">
<input type="text" name="first_name">
<input type="text" name="item">
<input type="submit" value="Add item">
<input type="submit" value="Submit">
</form>
Clicking 'Add Item' or pressing Return/Enter inside name="item" will add another form field.
Final Note
As far as I can tell, there isn't a way to detect which form field triggered a form submission. If you need to prevent submitting a form that has multiple buttons and/or from Enter/Return, you'll need to use <input type="button"> and bind event handlers to the form fields you want to stop form submission from.
If you have multiple submit buttons, the way you can tell is by giving each of them a unique name attribute, like this:
<input type="submit" name="submit1" value="Submit 1"/>
<input type="submit" name="submit2" value="Submit 2"/>
<input type="submit" name="submit3" value="Submit 3"/>
The one that is focused is sent along with the form submit, so if you clicked the one with a name of "submit2", that would come through in the form POST (or GET). If enter is hit, the first button in the source (in this case submit1) is considered the default and is sent along. You could set it to display:none to use as a dummy for detecting whether enter was pressed vs actually clicking a submit button.
EDIT:
In response to your comments, to capture the enter key getting pressed in certain elements you can do this with jQuery.
Note, you'll need to give first_name and add_item id attributes, and turn add_item into a type="button" instead of type="submit".
HTML:
<form action="" method="POST">
<input type="text" name="first_name"/>
<input type="text" id="item" name="item"/>
<input type="button" id="add_item" value="Add item"/>
<input type="submit" value="Submit"/>
</form>
JS:
$("#item").keydown(function(event){
if(event.keyCode == 13) {
addFields();
event.preventDefault();
event.stopPropagation();
}
});
$("#add_item").click(function(event) {
addFields();
});
You could set the onclick event on each element you are interested and call a javascript function with a different parameter for each element clicked.
From that function you send the idendifier of the button to the server side as a parameter
Just put a different name on each submit button, whichever one was clicked will be submitted (i.e. its name/value pair) with the form. Forms have worked like this since the begining of (WWW) time.
If the form is sumitted by enter or other keypress, no the first submit button name/value pair will be submitted.
Edit
Re-reading your question, you may want to determine how the form was submitted before it is sent. A click listener on the form can remember the last submit button clicked, but in Firefox, pressing enter in an input dispatches a fake click on the first submit button so you can't detect it.
I think you can't do it reliably other than using the basic method suggested above or Jordan's hidden submit button. If you say why you need to do this, perhaps more help can be provided.
here's an option if you don't mind using jQuery:
example: http://jsfiddle.net/U4Tpw/
use something like
$('form').submit(function() {
// identify the form by getting the id attribute
handleWhichForm($(this).attr('id'));
});