Form onsubmit() does not function - javascript

I want to control my form for the required input texts, and I have made a function in javascript. But when I click the button, and I havent fill the required field nothing the message do not appear, and I can go to the other page.
the function is:
function Validate(){
// create array containing textbox elements
var inputs = [document.getElementById('firstname1')];
var error;
for(var i = 0; i<inputs.length; i++)
// loop through each element to see if value is empty
{
if(inputs[i].value == '')
{
error = 'Please complete all fields.';
alert(error);
return false;
}
}
}
and the part of form is:
<form name="password" onsubmit="return Validate()" method="post" id="password" action="#">
<input type="submit" value="Proceed" id="submit1" onclick="displayform2()" class="button" style=" margin-top: -40px;margin-left: 60%;width: 25%" disabled>
I have noticethat if I put off the onclick method in the button it works, but I should have this method at the button...How can I solve this?Please help me
function displayform2() {
/*For desktop*/
if (document.getElementById('desktop1').style.display=='block') {
document.getElementById('desktop1').style.display='none';
document.getElementById('desktop2').style.display='block';
document.getElementById('desktop3').style.display='none';
}
/*For mobile*/
if (document.getElementById('mobile1').style.display=='block') {
document.getElementById('mobile1').style.display='none';
document.getElementById('mobile2').style.display='block';
document.getElementById('mobile3').style.display='none';
}}
It opens another form in the page...so when I click the button the first form dissapeared and the second form is displayed

You have this: var inputs = [document.getElementById('firstname1')];
Then you try to loop through that. I'm betting firstname1 is a field, so it's either null (if that field doesn't exist) or an array with only one element (the field). It looks like you are trying to check all required fields, so that won't work.
I'm not 100% what you ultimately want to do, but it will likely be much easier if you use a framework like jQuery; otherwise, you are going to have to do some complicated case-handling for different browsers.

Nowhere in your code do you call submit. That is why the function in the onsubmit handler is not triggered. If you want the button to submit the form, it would need to be a submit button.

Your example is a little unclear. For example, you are trying to validate whether a value has been entered into the input "firstname1", but you don't have markup for that element in your HTML.
I suspect what you are trying to do is to validate whether the form has been filled out or not. Something like the following (which validates input "firstname1") will do the job:
$(document).on("click", "#submit1", function(){
if($("#firstname1").val() == "" || $("#firstname1").val() == null){
alert("Please complete all fields.");
}
});
Working example here
The above requires jQuery, but can also be converted into vanilla JavaScript.
Load the jQuery library in the "head" section of your document by including the following code:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

Related

How to display "Please fill out this field" for all empty and required fields in html form?

I have a form as shown in the fiddle https://jsfiddle.net/vrn7zx5h/3/ in which I want to show the warning sign "Please fill out this field" at the same time for all unfilled required fields.
I found the answer on SO (as shown below) but i am not sure how to integrate with the fiddle.
function checkName(val){
if(/^[^-\s][\w\s]+$/.test(val)){
return true;
}else{
if(val.length != 0){
return false;
}
}
}
Problem Statement:
I am wondering what changes I should make in the fiddle so that the above pasted SO answer works with the fiddle.
Here is a JS fiddle that will show all error at one time. It is just barebone and not fancy. You'll need to make it fancy on your own. I also disabled the built-in validator as well with novalidate in the form tag.
https://jsfiddle.net/6kxc9hmq/1/
FYI: I also did not put in the functionality to hide the error message on next run, if the input now satisfies the condition.
Basically, I attached a submit event handler to the form and if the validator returned false, I told the form to not submit. Works only on IE9+ (I think) all the other browsers are usually fine with this method. The validator is basically just checking if the value of the input met the condition that I specified.
document.getElementById('form').addEventListener('submit', function(e) {
if(!validate())
e.preventDefault();
});
I think it should look like this, if I understand what you mean
<form action="">
Username: <input type="text" name="usrname">
Password: <input type="password" name="Password">
<input type="submit">
</form>
<p><strong>Note:</strong> The required attribute of the input tag is not
supported in Internet Explorer 9 and earlier versions.</p>
<script>
// append the listeners
document.forms[0].addEventListener('submit', function(evt){
if([
checkName(this.querySelector('[name="usrname"')),
checkName(this.querySelector('[name="Password"'))
].some((v)=>v)) {
evt.preventDefault()
}
})
// check is empty, then notify
function checkName(element){
// if you just have to check if is empty, this is enough
if(element.value) {
return
}
notify(element)
return true
}
// print the message
function notify(element) {
if(element.nextElementSibling.classList.contains('notify')) {
return;
}
element.parentNode.insertBefore(
Object.assign(document.createElement('p'),
{
className: 'notify',
innerHTML: 'Please fill out this field for all empty and required fields'
}
), element.nextSibling)
}
</script>
In your form, add empty divs after each input element. And you can conditionally display messages in the div in your validation. E.g if(name ==‘ ‘){div.innerHTML = ‘please enter your name’}
The required Attribute
Add the required attribute to your form.
The required attribute tells the browser to only submit the form if the field in question is filled out. Obviously, this means that the field can’t be left empty, but it also means that, depending on other attributes or the field’s type, only certain types of values will be accepted.

HTML "required" attribute for multiple button with multiple text field on same form

I have HTML form which has multiple button and multiple text fields on same form some thing like below.
Form: #myform
TextField1 ---> Button1
TextField2 ---> Button2
.. so on like more number of fields
I want to apply "required" attribute only specific button to specific textfield (Button1 for TextField1 )
It will be grateful if someone provide solution in javascript by passing some parameter to perform this validation
According to mozilla "required" is not included. So "required" is not allowed on element "button". You can add, but it will not add validation. For button and i would use validation with javascript.
I found solution to suit my requirement which I asked in automated fashion, I am posting the code so that might be useful if someone searching solution like me
Calling function on button click
<input type="text" id="txtfield1" class="texttype0" th:field="*{txtfield1}" placeholder="Enter txtfield1">
<button type="submit" id="bt1" onclick="btn('txtfield1')" name="action" >Update</button>
And below is my javascript function
function btn(txtid) {
document.getElementById(txtid).setAttribute("required", true);
$('form#myform').find(
'input[type=text],input[type=date],select').each(
function() {
var name = $(this).attr('id');
if (txtid == name) {
$(name).prop("required", true);
} else {
$(name).prop("required", false);
document.getElementById(name).required = false;
}
});
}
This will search all element from a form and remove require attribute except the one which you passed in parameter.

Error handling for "required" keyword in html form submission

I am making a difficult design decision right now. I have a bunch of blanks in a form and two buttons in a html page, the two buttons are for "add" and "delete" data to/from a database (assuming that I have a method to retrieve data from the database and populate the form before deletion). I want to make a error handling mechanism such that
1) required fields must be filled before submission, and
2) empty form (hence record) cannot be deleted
The code I have is similar to the following:
<form id="fm" method="POST">
<input name="a" required>
<input name="b" required>
<!-- let's say I have 20 other blank fields -->
<button id="add"><input name="btn">Add</button>
<button id="delete"><input name="btn">Delete</button>
</form>
In my jquery, I have:
$("#fm").submit( function() {
return false;
});
$("#sbmbtn").click( function() {
$.post(............)
//and other magic tricks
});
If I were to put everything in .click function into the .submit function, javascript will automatically enforcing that "required" fields must be filled before submission. However, if i were to do this, the other button will behave oddly because both buttons are in the same form, and clicking on either one will trigger form submission, which is not desirable.
Long story short, I probably won't change the architecture much, what can I add or tweak to make sure the required fields are checked before submission?
required fields must be filled before submission, run this function before submission
function validate() {
var requiredFields = $('#fm input').filter('[required]');
var valid = true;
$.each(requiredFields, function(index, value){
if (value.value.length < 1) {
valid = false;
}
});
return valid;
}
and then use the return value from validate to make sure all fields are filled before running your submit function.
just disable the delete button if the form is empty
Edit: but all this will be useless if the user disables JavaScript so you have to have server side validation as well.

genvalidator: check for checkbox in form validation

I'm using genvalidator to have some tests on input fields in a form. Problem is I can't find a way to test if a checkbox has been checked. This is how all the fields are set:
frmvalidator.addValidation("name","req","Insert your name");
frmvalidator.addValidation("city","req","Insert your city");
frmvalidator.addValidation("phone","req","Insert your phone number");
This is my checkbox
<input type="checkbox" name="agree" id="agree "value="yes"/>
How can I make it mandatory with genvalidator?
This is the part that handles the form process (in short: if there aren't errors, it's ok):
if(empty($name)||empty($city)||empty($phone)||BLAHBLAH)
{
$errors .= "\n Mandatory field. ";
}
if(empty($errors))
{
// send the email
}
It tried with this JS code with no luck:
function validate(form) {
if(!document.form1.agree.checked){alert("Please check the terms and conditions");
return false; }
return true;
}
If possible I'd like to use genvalidator functions. :)
You are expending a lot of energy trying to make the javascript plugin work.
Would you consider working with jQuery? If you haven't yet kicked its tires, it's a lot easier than it sounds -- and much more uniform / faster to type than plain js.
To use jQuery, you only need to include the jQuery library in the document, usually in the head tags thus:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
Then, you can easily create you own verification routines, with FULL control over what you are doing.
Here is a working example for you to study. As you can see, the code is pretty minimal.
When the Submit button (#mysub) is clicked, we quickly check each field to see if it validates. If any field fails validation, we can return control to the user with the field colored and in focus.
If all fields pass validation, then we issue the submit() method on the form ID, and off it goes (to the location specified in the action="somepage.php" attribute).
Note that I added some quick/dirty code at bottom to remove any css colorization from failed validations. This code runs every time a field is exited, regardless whether the field has validation coloring or not. This is not very efficient (although it certainly won't hurt anything) and is only intended to demonstrate what is possible.
Hmmmmm. I think it would be more efficient to have a class with certain attributes, and add/remove that class if fail validation. Okay, I liked that idea enough that I created a new jsFiddle using that method to demonstrate what that would look like.
jsFiddle here
HTML:
<form id="fredform">
First Name: <input id="fname" name="fname" type="text"/>
Last Name: <input id="fname" name="fname" type="text"/>
Email: <input id="fname" name="fname" type="text"/>
<input id="mysub" type="button" value="Submit" />
</form>
jQuery:
arrValidate = ['fname','lname','email']
$('#mysub').click(function() {
var nextFld, i ;
for (i=0; i<arrValidate.length; i++){
nextFld = arrValidate[i];
if ( $('#'+nextFld).val() == '') {
alert('Please complete all fields. You missed the [' +nextFld+ '] field.');
$('#'+nextFld).css({'border':'1px solid red','background':'yellow'});
$('#'+nextFld).focus();
return false;
}
}
//if it gets here, all is okay: submit!
$('#fredform').submit();
});
//Remove any css validation coloring
$('input:not([type=button])').blur(function(){
$(this).css({'border':'1px solid lightgrey','background':'white'});
});
Note that there is also a jQuery validation plugin that looks very professional. I haven't played with it myself, always preferring to code my own stuff, but here is the link:
http://jqueryvalidation.org/documentation/
Note the very cool demo
Just so you know what to expect: implementing this plugin would be more difficult than the methodology I suggested above.
` ANSWER TO YOUR COMMENT QUESTION: `
Regarding your comment and the code posted at pastebin:
(Sorry for the long answer, but I want it to be clear. Please read carefully.)
(1) Please wrap your javascript code in a document.ready function. This is my fault; I should have added it to my code example. Otherwise, the code will execute before the DOM fully exists and event triggers will not be bound to the controls (because they do not yet exist in the DOM). Therefore:
arrValidate = ['checkbox']; //a global variable
$(document).ready(function() {
$('#submit').click(function() {
var nextFld, i ;
for (i=0; i<arrValidate.length; i++){
nextFld = arrValidate[i];
if ( $('#'+nextFld).val() == '') {
alert('Please complete all fields. You missed [' +nextFld+ ']');
$('#'+nextFld).css({'border':'1px solid red','background':'yellow'});
$('#'+nextFld).focus();
return false;
}
}
//if it gets here, all is okay: submit!
$('#contact_form').submit();
}); //END #submit.click
}); //END document.ready
(2) Your checkbox still has the value="yes" attribute that breaks the javascript. Please change this:
<input type="checkbox" name="checkbox" id="checkbox" value="yes" /> <small>Ho
to this:
<input type="checkbox" name="checkbox" id="checkbox" /> <small>Ho
(3) There is no need to have type="submit" for your <input value="Invia"> button, nor is there a need for a name= attribute on that control.
First the name= attribute: it is only useful when passing data from that control to the PHP(?) file that processes your form: ($_SERVER['SCRIPT_NAME']). The name= part is the variable name, and the value of the control is the variable value. The button has no data to pass along, so does not need to have a variable name assigned to it.
Next, the type="submit": This is not required, because you can use jQuery to submit the form any time you want. In the old days, before javascript/jQuery, we had forms. Back in those days, the only way to make the form submit was to use the type="submit" attribute. There was no such command as: $('#myFormId').submit(); -- but today there is. So change that attribute to type="button" and let jQuery submit the form for you. Trust me, this works!
Another thing to consider: once you use type="submit" you must deal with the form's default actions when clicking that button. You cannot simply return control to the user when there is an error, because the form has been told to submit. (You must use event.preventDefault() to override the default behaviour -- you can read about that later.)
(4) Checkbox values must be checked using one of these methods. Checkboxes do not have a value. This is my fault again, I should have written a checkbox into my example.
$('#submit').click(function() {
var nextFld, i ;
//Validate the checkbox:
if ( $('#checkbox').is(':checked') == false ) {
alert('You must read the informativa and check the checkbox at bottom of form');
return false;
}
//Validate the rest of the fields
for (i=0; i<arrValidate.length; i++){
(5) jQuery's submit() method won't work IF any element uses =submit as either its name= or id= attribute.
This is a weird thing, but you need to know it. I just learned it (again) while troubleshooting my jsFiddle example.
If you want to use jQuery to submit your form (and we do) via the .submit() method, then no element in your form can have the name= or id= attribute set to "submit". The INPUT button had both name= and id= set to submit; that is why it wasn't working.
Reference: http://blog.sourcecoder.net/2009/10/jquery-submit-on-form-element-does-not-work/
See the revised code example in the jsFiddle:
Revised jsFiddle here
Please Please Please study the above jsFiddle. You should be able to dump the genvalidator plugin entirely. If you understand the jsFiddle completely, you will be in a new place as a programmer.
If you're using jQuery, try checking this way:
function validate(form) {
if(!$('[name="agree"]').prop('checked')){
alert("Please check the terms and conditions");
return false;
}
return true;
}
or try using
function validate(form) {
if(!$('[name="agree"]')[0].checked){
alert("Please check the terms and conditions");
return false;
}
return true;
}
This is untested but I think it would look something like this:
function DoCustomValidation() {
var frm = document.forms["myform"];
if(document.form1.agree.checked != true) {
sfm_show_error_msg('The Password and verified password does not match!',frm.pwd1);
return false;
}else{
return true;
}
}
Note that you must customize this line to have the correct name of your own form:
var frm = document.forms["myform"];
Plus, you also need to associate the validation function with the validator object:
frmvalidator.setAddnlValidationFunction("DoCustomValidation");
Source: genvalidator documentation
Since you've tagged the question with JQuery, this should work for you:
function validate(form) {
if ($("#agree :checked").length < 1) {
alert("Please check the terms and conditions");
return false;
}
return true;
}
I tend to use this approach because it also works for multiple checkboxes or radio button groups as well. Note, however, that it does not care about what was checked, just that something was checked . . . in the case of a single checkbox, this acts as a "required to be checked" validation as well.
Add a new div for error location above your input tag like this :
<div name="formname_inputname_errorloc" class="errorstring">
//<your input tag goes here>
Make sure u have the css for errorstring class in your css file. and the other req js files
Try to search the demo for gen validator it has been totally explained in the demo
frmvalidator.addValidation("agree","selmin=1","Please select checkbox");

javascript getElementById() for loop (empty textbox validation)

i have the following code that validate against empty textboxes. If there are empty ones, the form will not be able to submit successfully.
However,I cannot seem to get the alert to popup after clicking submit looping through the elements to find if there are any empty boxes to fill in.
any advice/correction on the looping?
Move your onSubmit into the tag instead of the Submit button, for one... it's not firing the event at the proper time. It should be like:
<form action="whatever" onSubmit="return submitform();">
Also change the last line of the function,
else document.forms[0].submit();
to
return true;
This should solve the problem of it not running properly, and not intercepting the submission of the form.
Also, you shouldn't have multiple items with the same ID. It's not valid HTML and can cause problems with some browsers *cough*IE*cough*, though you'd probably get away with it in this case.
You may want to read the jsfiddle documentation.
Here you'll find a working version of your code. The (corrected) function:
function submitform() {
var msg = ''
,elems = document.getElementById('tasks').getElementsByTagName('input');
for (var i = 0; i < elems.length; i++) {
if (elems[i].id && elems[i].id.match(/^t/i) &&
elems[i].value.replace(/^\s+|\s+$/,'') === '')
{
msg += elems[i].id+ ' is empty!\n';
}
}
if (msg.length > 0) {
alert("one or more of the inputs is/are empty\n"+msg);
return false
}
else alert('we are cool');
return true;
}
A bit more worked out: http://jsfiddle.net/GbX8m/4/
You are not following dom rules. ID should be uniquer for each element. You should have unique id. Read xhtml guidelines.
document.getElementById will return one element not array. If you want to apply on group use function which apply on group like document.getElementsByClassName.
form tab should have action . if you want it to on same page use. action="#"
Fire submit form on form submit not button click and submitform should return true of false depending on if form is valid or not.
If that is for education purpose then good. Otherwise use framework like jquery those have many function which will reduce your work.

Categories

Resources