Call a function after Html5 Validation success - html

I have Some text boxes and one submit button. I have Used HTML5 'required' validation. Its working fine. Now I want to call a function in button click when HTML5 validation does not find any Error. When The required field is not provided the button click will not call the function.

You can use the form.onsubmit handler. Assuming the form's ID is form:
var form = document.getElementById("form");
form.onsubmit = function() {
//Pre-submission validation.
//Return true or false based on whether the validation passed.
//return false will prevent the submission the form.
};

You're going to need some extra help to do this, it could be in the form of plain javascript. Personally, I'd use jQuery to help out as it will make things easier for you and account for any cross-browser consistencies. Whether or not you want to use jQuery your is choice, whether it's appropriate only for this is another conversation, the following example is just a demonstration.
Here's a hypothetical example using jQuery that achieves your validation listening functionality:
HTML
<form>
<input type="text" class="input-text" required>
<input type="text" class="input-text" required>
<input type="submit" id="submit" class="input-button" disabled>
</form>
​
JS
$textInputs = $('input.input-text');
$textInputs.on('keyup', function() {
var $validTextInputs = $('input.input-text:valid'),
$submit = $('#submit');
console.log($textInputs.length, $validTextInputs.length);
if($textInputs.length === $validTextInputs.length){
//all text fields are valid
$submit.attr('disabled', null);
} else {
//not all text fields are valid
$submit.attr('disabled', '');
}
});​
CSS (only let's us know, visually, when the input is valid)
.input-text:valid {
background: green;
}​
See the example in action here: http://jsfiddle.net/m6QXc/

Use jquery to trigger function after HTML5 form validation
<form id="myForm">
<input type="text" class="input-text" required>
<input type="submit" id="submit" class="input-button" disabled>
</form>
$("myForm").submit(function(){
// Your code
})

Well, you could try this: fiddle example extend it as you need, used jQuery though. You can add whatever you want inside:
$('#exampleForm').submit(function(e){
e.preventDefault();
// here you can call your own js methods, send form with ajax?
// or what ever you want
});

Related

Readonly and Required on one input field

For a webapp i'm currently developping, i need to hide the standard IOS keyboard when focusing on a textbox.
This can be done simply by adding the 'readonly' tag, and opening my custom input using a onClick function.
<form method="post" action="" enctype="multipart/form-data">
<input type="text" id="test123" onClick="doSomething();" readonly required />
<button type="submit" value="submit">
Save
</button>
</form>
(JSFiddle)
This works. Partially. By enabling the readonly i'm able to keep the keyboard hidden. But, another problem rises. When using the readonly, 'required' is not called. You can submit the form with an empty field, because its assumed a readonly field contains what it has to contain.
How can we possibly keep the readonly, and the required? We can't. We need a workaround.
Edit:
In regards to the possible duplicate.
The answer in THIS post is to add JQuery readonly with preventDefault. The problem with this is, that on ios devices the keyboard will stil open, which is ultimately our goal. The keyboard must not open, and still it should be a required field. In theorie, i think this can be achieved using Javascript validation. But that means, my submit button will be calling a js function, while it has to be calling our php function to submit our data.
Here's how i solved this problem. I tried to make a JS validator, as simple as possible.
$('#dataInput').submit(function (e) { //Form is submitted, it calls this function automatically
var empty = 0;
$('input[type=text]').each(function(){ //Check each input (had to be done like this, because i dont know the amount of input beforehand)
if (this.value == "") { //The textbox is empty
empty++;
}
})
if(empty === 0){ //No empty textboxes
}else{
alert(empty + ' empty input(s)'); //There are empty textboxes
e.preventDefault(); //Prevent the submit from happening
}
});
You can check out the fiddle here
You can set and remove READONLY before enter or leave the field.
$(".datepicker").on("touchstart", function(e) {
$(".datepicker").attr("readonly", "readyonly")
})
$(".datepicker").on("blur", function(e) {
$(".datepicker").removeAttr("readonly")
})
First Approach: You can assign a dummy value and then check in the backend whether the value is changed or not, if it is not changed, you can show an error message. Other wise save into database.
<form method="post" action="" enctype="multipart/form-data">
<input type="text" value="dummy" id="test123" onClick="doSomething();"
readonly required />
<button type="submit" value="submit">
Save
</button>
</form>
Second approach: when you fire the onclick event of the input field, you can remove the readonly attribute using the following code.
function doSomething()
{
$("#test123"). removeAttr("readonly");
}

HTML form with different page redirection depending on input

I want to have a box in HTML such as this one:
Particular thing, I need to do this using only HTML (no PHP or particular langage requiring server, or particular installation).
The reason for this is that it is meant to be used for HTML pages that will be opened from a USB key, not a website, and it has to be usable by any non-expert person. So no web-server configuration or installation required, such as what would be required for PHP, if I am right.
Think about not using a Form, but just using a Javascript function.
I'm not sure if this probably is not possible due to security reasons, but it could be a solution...
function redirect() {
var input = document.getElementById("stuff");
window.location = input.value;
}
<span>NOM:</span>
<input type="text" id="stuff"></input>
<br>
<input type="button" onclick="redirect()" value="Submit"></input>
I managed to do what I needed thanks to Anders Anderson's answer. Here is the code for those interested in doing similar thing. First, for the Javascript
function redirect() {
var answergiven = document.getElementById("answergiven");
var realanswer = document.getElementById("realanswer");
var nextpage = document.getElementById("nextpage");
if(answergiven.value.toLowerCase() == realanswer.value.toLowerCase()){
window.location = nextpage.value;
}
else{
alert('Wrong answer, please try again.');
}
return false; // prevent further bubbling of event
}
And for the HTML part, there are two hidden variables that determine the real answer, and the next page to go to, and the text field for the answer
<form name="myform" onSubmit="return redirect()">
<span>Réponse:</span>
<input type="text" id="answergiven" />
<input name="tosubmit" type="submit" value="Submit" />
<input type="hidden" id="realanswer" value="theanswer" />
<input type="hidden" id="nextpage" value="thenextpage.html" />
</form>

HTML5 form is not getting submitted

I have the following code to submit a form. If I use the event listener function name as submit, the form does not get submitted. If I use any other name, it will. Should not I use any HTML5 keyword like submit in JavaScript as function name? In this case submit is a HTML5 keyword which can be used as a type of any INPUT element.
<form onsubmit="submit()">
<input type="email" name="email" />
<input type="submit"/>
</form>
function submit() {
var f = $('form').serialize();
alert(f);
}
You're already using jQuery here so a more elegant solution to the whole problem would be:
// HTML
<form name="my-form">
<input type="email" name="email" />
<input type="submit"/>
</form>
Then have a separate JS file:
//Js
$(document).ready(function(){
$('form[name="my-form"]').submit(function(e){
var f=$(this).serialize();
alert(f);
});
});
This also gives you extra options to prevent the form from submitting cleanly; add this at the end of the submit(){ } function.
e.preventDefault();
Update
As the OP pointed out the original question was whether the function name submit() can be used as the onsubmit attribute in a form.
This answer suggests that it cannot, as carrying out the following:
document.form['my-form'].submit();
Would be a valid way to trigger submission of the form; thus that method name can't then be included in the HTML. I am searching now for a better source to confirm this for sure I have found a similar source on Mozilla Developer Network which confirms the code above but doesn't explicitly define that the keyword submit cannot be used.
You know, there is another way to do this. You could separate your html from javascript enritelly.
<form id="form">
<input type="email" name="email" />
<input type="submit"/>
</form>
//Rest of your code
<script>
$(function() {
$('#form').submit(function() {
var f = $('#form').serialize();
// do your stuff
return true; // return false to cancel form action
});
});
</script>

Can a form submit be disabled if a HTML file input field is empty?

In a form which contains only a
<input id="fileInput" name="BugReport" type="file" />
input field, I would like to disable the Submit button if the file input is empty (no file was chosen yet). Is there a recommended way to do this?
Add the required attribute to the input. It'll only work in browsers that support it, so you should have a JavaScript alternative (<form onSubmit="if(document.getElementById('fileinput').value == '') return false;"> or something along those lines).
Checking for whether the file input's value should always work.
if (document.getElementById("fileInput").value == "") .....
the true path of the file will be obfuscated for security reasons, but the value should always return something when a file is selected.
You can do it with JavaScript. The following code assumes you have given an id of "s" to the submit button of the form:
document.getElementById("fileInput").onchange = function() {
if(this.value) {
document.getElementById("s").disabled = false;
}
}
Obviously, you'll need to have the submit button disabled to start off. For example:
<input type="submit" id="s" disabled>
With this the best way is to have Javascript validate all the inputs as they are changed. So as the input gets changed (you can use the on change event) in Javascript enable or disable the button depending.
<input id="fileInput" name="BugReport" type="file" onchange="validateForm()"/>
This should call the javascript button which will check the input is it has a valid file and if so enable the submit button.
You can do this using jQuery
<script src="/Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script>
$(function () {
$('#submit').attr("disabled", true);
$('#fileInput').change(function () {
if ($('#fileInput').val().length == 0)
$('#submit').attr("disabled", true);
else
$('#submit').attr("disabled", false);
});
});
</script>
<input id="fileInput" name="BugReport" type="file" />
<input id="submit" type="submit" />
hope this helps
yeah, you can add something like:
<input type="submit" onclick="if (window.getElementById('fileInput').value == '') return false" />
or start with a disabled submit button and enable it when the file input is clicked and the value is different than the empty string.
check this jsbin to see what the value of a file input is (its a 'fakepath' and the name of the file)
If you are using HTML5 just add required inside input tag:
<input type='file' required />
Example:
<form>
<input type='file' required />
<button type="submit"> Submit </button>
</form>

Set a form's action attribute when submitting?

How do I change a form's action attribute right after clicking the submit button?
<input type='submit' value='Submit' onclick='this.form.action="somethingelse";' />
Or you can modify it from outside the form, with javascript the normal way:
document.getElementById('form_id').action = 'somethingelse';
There's a simple way to do this if you only need to support modern browsers: on your submit button, add a formaction="/alternate/submit/url" attribute like so:
<form>
[fields]
<input type="submit" value="Submit to a" formaction="/submit/a">
<input type="submit" value="submit to b" formaction="/submit/b">
</form>
It also works on <button> tags.
The gotcha is that old versions of IE (<10) and the Android Browser (<4.0) do not support it. So, if you need to support older browsers, then the existing JS answers will probably work better for you.
More info: http://www.wufoo.com/html5/attributes/13-formaction.html
You can also set onSubmit attribute's value in form tag. You can set its value using Javascript.
Something like this:
<form id="whatever" name="whatever" onSubmit="return xyz();">
Here is your entire form
<input type="submit">
</form>;
<script type=text/javascript>
function xyz() {
document.getElementById('whatever').action = 'whatever you want'
}
</script>
Remember that onSubmit has higher priority than action attribute. So whenever you specify onSubmit value, that operation will be performed first and then the form will move to action.
Attach to the submit button click event and change the action attribute in the event handler.
You can do that on javascript side .
<input type="submit" value="Send It!" onClick="return ActionDeterminator();">
When clicked, the JavaScript function ActionDeterminator() determines the alternate action URL. Example code.
function ActionDeterminator() {
if(document.myform.reason[0].checked == true) {
document.myform.action = 'http://google.com';
}
if(document.myform.reason[1].checked == true) {
document.myform.action = 'http://microsoft.com';
document.myform.method = 'get';
}
if(document.myform.reason[2].checked == true) {
document.myform.action = 'http://yahoo.com';
}
return true;
}
HTML5's formaction does not work on old IE browsers. An easy fix, based on some of the responses above, is:
<button onclick="this.form.action='/PropertiesList';"
Account Details </button>
You can try this:
<form action="/home">
<input type="submit" value="cancel">
<input type="submit" value="login" formaction="/login">
<input type="submit" value="signup" formaction="/signup">
</form>