Ajax form submit after validating input elements - javascript

I have a form which collects some information using text boxes. Some text boxes have a strick pattern, e.g. few input boxes take only numbers.
I was able to add validation using pattern attribute of input field. http://www.w3schools.com/tags/att_input_pattern.asp
However, when user submits the form I need to do a ajax post request to a different end point. So, I think I have to make a call to preventDefault() method to prevent default form submit.
But when I call preventDefault(), it also disables validating input fields.
How can I achieve validating fields and make a ajax request, only if the input fields pass the validation.

You can either way use this:
First change the input[type="submit"] to this:
<button onclick="submitThis()">Save</button>
function submitThis() {
var firstInput = $("#idoffirstinput).val(); // basic validation
if(firstInput == "correctinput") {
$.ajax({
// send the ajax form
})
}
}
You can seperately validate each input using the technique provided there, or the one I provided. The jQuery error will be same; I mean the validation.
Use this:
if(firstInput == "correctinput") {
// ajax form
} else {
// show the error popup!
}
The plus point for this one is that you can style the error dialouge popup too. Like
$("#errordiv").css("border", "1px solid #hexcode");
And everything else is same!

HTML and jQuery:
<form id="details">
Phone no: <input type="text" id="phone_no" pattern="[A-Za-z]{3}">
<input type="submit" id="submit">
</form>
var input = $('#phone_no').val();
if(input != '')
{
var YOUR_URL = 'www.example.com';
var formData = $('#details').serialize();// If you want to pass that data to that URL
$.post(YOUR_URL,formData,function(result){
});
}
else
{
return false;
}

Related

How to manually trigger bootstrap "required" tooltip alert?

When you submit a form via <input type="submit">
and some input with required attribute was empty, a little box appears near to the missing input box saying "Please fill out this field" or something similar (I use it in Italian so I don't know the exact wording used in English).
I need to manually trigger this tooltip alert using JavaScript, any idea how to achieve this?
The form validation is provided by HTML5, it's not related with Bootstrap, to disable the default form validation provided by the browser you have to work with the form containing the input, for example using the attribute novalidate will disable the default form validation provided by the browser. If then you want to use a custom form validation function you can use the onsubmit event on the form, so for example you will have something like:
<form onsubmit='return submitForm(this);' novalidate='novalidate'>
<input type='text' required>
<input type='submit'>
</form>
By doing this when the form is submitted you are passing the function submitForm the submitted form, so that this function is able to iterate through the elements of the form to check them.
Something like:
function submitForm(formToValidate){
var formValid=true;
var inputs = formToValidate.getElementsByTagName("input");
var errorDescription;
for(var i=0; i<inputs.length; i++)
{
var inputValid=true;
switch(inputs[i].type)
{
case "number":
if(inputs[i].hasAttribute("required")&&inputs[i].value=="")
{
inputValid=false;
errorDescription="Required field";
}
/*Check other attributes here (max, min, step, etc.)*/
break;
/*Check other types of input here*/
}
if(!inputValid)
{
markInputAsNotValid(inputs[i],errorDescription);
formValid=false;
break;
}
}
return formValid;
}
Note that the value returned by the function submitForm is used by the browser to determine if the submission was successful.
For more information: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation

How can i show a validationMessage (for an input element) programmatically without a Form?

Im not sure if this is possible without using a form.
But I would like the browser to render the validation errors.
Again, I am doing this programmatically without a form.
i.e. No Form tag, and no submitting. Just straight-up scripting.
Updated
I would like to validate input fields, such as:
<input value="123" maxlength="5"/>
<input value="hllo wrld" spellcheck="true"/>
If you wan't to validate that fields on page load without any additional submit/click event this can be possible solution :
$( document ).ready(function() {
$("#fieldDiv input").each(function() {
if(!isNaN(this.value)) {
alert(this.value + " is a valid number");
}
});
});
Idea is to traverse all input fields and perfom validation. You can use custom attributes to know what validation to use.

Pass name in jQuery form submission

I do not know why the following line will not function properly:
$('form[name="updateNetwork"]').unbind('submit').submit();
I can submit my form with
$("form").unbind('submit').submit();
However doing so will not pass the name attribute of the form which my backend code must identify in order to properly process the form submission. Any assistance would be greatly appreciated.
Thanks
It seems that you have only one form in your page, and that the only reason you're trying to select it with the name attribute in jQuery is so that jQuery will send the name of the form to the server.
Well, that won't work. Once you get a reference to your form via jQuery, it doesn not matter which selector you had used. If what you want is to send a name parameter to your backend code with the form name, use a hidden input inside the form:
<input type="hidden" name="form-name" value="updateNetwork" />
Then, you can get a reference to the form any way you want. The best one, as stated by #anvlasop, is to give your form an id attribute.
EDITED
You were creating the jQuery form object in a wrong way. If you have this:
<input type="submit" name="updateNetwork" />
then you can't do this:
$('form[name="updateNetwork"]).submit();
I assume that you're calling this method, submit(), inside the event handler of the submit event. Don't do that! What you should do, is to only canll preventDefault if there is an error in the validation, and let the form be sent otherwise:
//Never do this:
$('form').bind('submit', function(e) {
var valid;
//code to validate
e.preventDefault();
if (valid) $('form').unbind('submit').submit();
});
Do this:
$('form').bind('submit', function(e) {
var valid;
try {
//code to validate
} catch (error) {
valid = false;
}
if (!valid) e.preventDefault();
});
This also will prevent the sending of the form is there is an exception during validation.
You can give an id to your form. Try something like this html code:
<form id='form_id'>
//your form elements here...
</form>
Then, with jQuery you can have a reference to the form like this:
$("#form_id").unbind('submit').submit();

Fetching clientside HTML Table data to server side PHP script on form submission

I've an html form with multiple elements. Now, in particular to which I want your attention are two dropboxes and beside that an "add" button.so, once the user makes selection from the dropdown and presses the "add" button, it'll add the data to a table and that table will show up just below those dropboxes.So, basically user can add multiple data through the dropdowns and see it in a table. Now, the problem arises when I want to retrieve the data from this table when the form gets submitted. I'm not sure if $_PHP[''] would be able to fetch the data from the table I created.
So, as an alternative I'm trying to pass the data using AJAX when form gets submitted!
HTML:
<form name="input" id="formToSubmit" action="process-host.php" method="post" enctype="multipart/form-data">
/* Form data goes here*/
<input type="button" class="submit" value="Submit Request" onclick="valField(this.form); "/>
valField() method validates
and submits the form.
JS:
function valField(form) //field validation for the form before submit
{
/*Validation code goes here*/
//if(validated){
$("#formToSubmit").submit(function(e) { //this.submit(function(e)){
e.preventDefault();
var tableForNew = new Array(); //to store the infoDisplayTable data
$('#infoDisplayTable1l tr').each(function() {
tableForNew.push($(this).find("td:first").html());
tableForNew.push($(this).find("td:second").html());
});
// Get all INPUT form data and organize as array
var formData = $(this).serializeArray();
// Encode with JSON
var tableForNew1 = JSON.stringify(tableForNew);
// Add to formData array
formData.push({name: 'tableForNew', value: tableForNew1});
// Submit with AJAX
$.ajax({
url: "./process-host.php",
data: formData,
type: 'post',
success: function() {
alert("BOOM! IT WORKED;");
}
});
});
On the server side, in process-host.php,
$tableForNew = json_decode($_POST['tableForNew']);
This obviously isn't working out, so when I'm debugging with Firebug, I can see that it is not going inside the submit function. It just submits the form, without going through inside code! and thats why its not posting any table data to server and gives error notice Undefined index: tableForNew .
So, what can I do here to make it work? any suggestions?
When you use an inline onclick handler you need to return false or else the default action will be triggered (submitting the form).
However, the way you have this setup right now the valField function will just define the submit handler and return - which means that even if you return false you will have to click the button a second time to trigger the submit event, which will also fire the valField function and redefine the submit handler (inception!).
You should remove the onclick handler you have on button element, move the submit handler out of the valField function, and only do the ajax call if the form is valid.
Well, making AJAX call while submitting the form didn't workout for me after all, but I did succeed in fetching the data from HTML table on the server side somehow! The solution that worked for me now is adding hidden fields to the form.Basically I'm adding hidden <input> fields to form when user inputs values and presses "Add" button, so it's in "Add" button's onClick event handler! Here's how that function looks like,
function addData1(){
if($("#consumerDropDown").val() != "" && $("#authenticationTypeDropDown").val() != "")
{
$("#infoDisplayTable1").show();
$("#infoDisplayTable1").attr("disabled", false);
$("#infoDisplayTable1").append("<tr><td >"+$("#consumerDropDown").val()+"</td><td>"+
$("#authenticationTypeDropDown").val()+"</td></tr>");
$("#tester").append("<input type='text' value='" +$("#consumerDropDown").val() + "----->"+$("#authenticationTypeDropDown").val() + "' name='dTable1"+ counter1+ "'>");
counter1++;
}
else
{
alert("Please make a valid selection from a drop-down before adding it to the list!");
}}
Here,note that I've defined counter1 as globel variable in JS file.Tester is id assigned to a <div> tag with attribute display:none. More on, I'm assigning name attribute of <input> tag dynamically(for example,here it'd be dTable10, dTable11 etc.), so it'd be easier to access it on server side! And finally just before submitting the form I'm passing that counter1 variable to hidden field just like how I did it above, $("#tester").append("<input type='text' name='counter1' value='"+counter1+"'>"); form.submit();
Server side:
$counterA = intval($_POST['counter1']);
for($i=0;$i<$counterA;$i++)
{
$createReq['comment'] .= $_POST["dTable1"."{$i}"]."\n";
}
Here basically I'm appending this values to a string variable. It's gonna loop through each item, and gonna append to the variable. So, this worked for me as a solution for now! But, I'd have been more satisfied if the AJAX call would had worked while submitting the form(what I was trying to do before)!

Custom form validation function on element with html 5

For a custom image selection tool I would like to create form validation based on html 5 form validation.
For example my form consists of the following elements:
<form class="cms-form" action="">
<table width="800">
<tr>
<td width="30%">Name:</td>
<td><input type="text" name="name" class="cms-input-text" maxlength="127" /></td>
</tr>
<tr>
<td>Image:</td>
<td><textarea name="icon" class="cms-input-file" data-file-resource="images" data-options="{"min":1,"max":3}">/location-to-image.png</textarea></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Next"/></td>
</tr>
</table>
</form>
I have a Javascript that changes the textarea (.cms-input-file) into some html to add images and hides the original textarea.
It looks something like this:
<textarea name="icon" class="cms-input-file" data-file-resource="images" data-options="{"min":1,"max":3}" style="display: none;">/location-to-image.png</textarea>
<ul class="cms-input-file-list">
<li class="cms-input-file-item" data-image="/location-to-image.png">
<img src="/location-to-thumb.png" alt="" class="cms-input-file-item-thumbnail"/>
<span class="cms-input-file-item-title">location to image</span>
</li>
<li class="cms-input-file-add">Add</li>
</ul>
Since I have allot of existing forms using html5 form validation I would like to validate this element using the default form validation within html5 supported browsers, but using a hopefully existing event.
I'm looking for something like this:
$('.cms-input-file').on('customValidateFunction', function () {
var options = $(this).data('options');
if($(this).find('> li.cms-input-file-item').length < options.min)
{
return [false, 'Add more images.'];
}
if($(this).find('> li.cms-input-file-item').length > options.max)
{
return [false, 'Remove some images.'];
}
return true;
});
Does anyone know if something like this is possible using default html 5 events or how would I go about adding this event to the submit event? To actually trigger the default browser validation look and feel.
-- edit --
So far I have made an attempt to get this result using a div element which hides the original element. But now I need to add a pattern to the element to match according to my options. Is this possible?
Current progress: http://jsfiddle.net/jeffreydev/YyEVu/
If I understand correctly what you need, I think you can achieve what you are trying to do using the pattern attribute of any input element.
I've created a very simple form in jsfiddle illustrating this.
The idea is that you update the value of your input with whatever data you have in your model when adding or removing images. The example, just adds one letter f per icon. Then, you can create a regex to match the expected valid results. In the example, pattern="f{1,3}" means that to be valid, the content can be "f", "ff", or "fff" but nothing else, which means that it'll only accept from one to three files to be sent.
You would be using just default html5 form validation, but you may need a bit of tweaking to get it working.
However, if you try this way, you should keep a couple of things in mind:
As explained in the specs, the patttern is compiled as a JavaScript regular expression with the global, ignoreCase, and multiline flags disabled
Setting the disabled property of your input so that the user can't change it would take it out of the form, and thus it won't be validated
Applying certain styles as *display:none" to the input element can cause errors when the validation fails and the browser tries to gain focus on the element.
I hope you this helps
You can install a submit handler on the <form>, and dispatch a custom event from there.
That will look something like this:
$('form.cms-form').on('submit', function(evt) {
var frm = $(this);
var allElements = $(this.elements);
$('#errors').empty();
var errors = [];
var arg = {
reportValidationError : function( msg ) {
errors.push(msg);
},
form : this
};
console.log("all elements: ", allElements);
allElements.trigger('customValidate', [ arg ]);
if( errors.length !== 0 ) {
showValidationErrors(errors);
return false;
}
return true;
});
Then, you can "hook" the customValidate event, and install your own logic...
$('textarea[name=icon]').on('customValidate', function(evt, reporter) {
var options = $(this).data('options');
// ... your validation here ...
// for example:
var txt = $(this).val();
if( txt.length < options.min || txt.length > options.max ) {
reporter.reportValidationError('error: "icon" min/max exceeded!');
}
})
Here's an example at jsFiddle.
Edit
You can style the error reporting, and tweak the code, to look and behave however you want it to. Here's an example.
A very good jquery plugin to validate your forms is Mike Alsup one's.
You will find it here: http://jquery.malsup.com/form/
It is documented, ajax compatible.
It can do serialization for one field or for all fields inside the form, so it is a big advantage regarding your problem you could need to handle fields validation and error logic with your forms.
You could add the blockUI plugin of the same author to enhance user's experience, and don't have to manage double submission of the form when javascript is enabled.
http://jquery.malsup.com/block/
Answer from 2022: Yes, it is possible without jQuery etc.
Most browsers support Constraint Validation API (even IE 11 according to "caniuse")
The recommended practice is to listen to input/submit events and then set validity flags on the input-box.
<form>
<input type="text" required id="answer">
<input type="submit">
</form>
Validation JS:
const nameInput = document.querySelector("#answer");
const form = document.querySelector("form");
function validate(e) {
if (nameInput.value == "42") { //correct!
nameInput.setCustomValidity(""); // empty means "no error"
}
else {
nameInput.setCustomValidity("Wrong answer!"); //show error text
e.preventDefault(); //prevent form submit
}
}
nameInput.addEventListener("input", validate);
form.addEventListener("submit", validate);
The input event fires even when the value is changed programmatically
P.S. Codepen to play with: https://codepen.io/jitbit/pen/XWYZjXO

Categories