required and button click javascript validation function not work? - javascript

I m applying two validation but both are not work
required validatation not work on input attribute
function validatation() not work
signup.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title></title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
<script src="signup.js"></script>
<script type="text/javascript">
function validatation() {
debugger
if (document.PersonalInform.txtfname.value == "") {
debugger
alert("Please provide your first name!");
document.PersonalInform.Name.focus();
return false;
}
}
</script>
</head>
<body>
<form id="txtPersonalInformation" name="PersonalInform" onsubmit="return (validatation());">
<h1>Personal Information</h1>
First Name:<input id="txtfname" name="txtfname" type="text" /><br/>
Middle Name:<input id="txtmname" name="txtmname" type="text" /><br/>
Last Name:<input id="txtlname" name="txtlname" type="text" /><br/>
<input id="btnnext" type="button" value="Next" />
</form>
</body>
</html>
OR
Below Validation Also Not Work
First Name:<input id="txtfname" name="txtfname" type="text" required /><br/>
signup.js
$(document).ready(function () {
$('#btnnext').click(function (event) {
$("#txtPersonalInformation").load("ContactInformation.html");
});
});
I add this line in web.config file
web.config
</system.web>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="none"/>
</appSettings>
I want to perform this javascript function validation but not work?
function validatation()

Here's what you want. You weren't submitting you form, as noted by Mendrika.
HTML Form:
<script src="https://code.jquery.com/jquery-3.4.1.min.js"> type="text/javascript"></script>
<form id="some-form" action="some-url" onsubmit="return validate()">
<label for="first-name">First Name:</label>
<input id="first-name" name="first-name" type="text"><br>
<label for="last-name">Last Name:</label>
<input id="last-name" name="last-name" type="text"><br>
<input id="btn-submit" type="submit" value="Submit">
</form>
JS Sample Validate function
function validate() {
if ($("#first-name").val() === "") {
alert("Provide a first name");
$("#first-name").focus();
return false;
}
if ($("#last-name").val() === "") {
alert("Provide a last name");
$("#last-name").focus();
return false;
}
return true;
}
https://codepen.io/el-sa-mu-el/pen/QWjVGvb
Note, this is not good code, but it works. You should read more about basics of JS and form validation.
Some other observations:
Your form is missing the action=" " tag which actually POSTs the data to some URL. Where is your data going?
You are mixing vanilla Java Script and JQuery. Use JQuery for DOM access if you already included it, with the $ symbol.
You have a signup.js function but also include a Javascript function in the <script> tags. You can move the validate() function into the signup.js
Better form validation with JQuery:
https://www.sitepoint.com/basic-jquery-form-validation-tutorial/

The reason nothing works is because your form is never submitted.
You just need to change the next button type to submit.
<input id="btnnext" type="submit" value="Next"/>

Related

My HTML form validator in Javascript doesn't seem to be working

I've written a validator for my HTML although I'm not sure where I'm going wrong.
What I'm trying to do below is determine if there is any text in the "First Name" box altogether. There is underlying css to the code but I believe my issue is surrounding my onsubmit and validate function as nothing in the javascript seems to be running once I click the submit button.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>NewPatientForm</title>
<link rel="stylesheet" type="text/css" href="NewPatient.css">
<script>
function validate() {
var invalid = false;
if(!document.Firstname.value.length) {
invalid = true;
}
if(invalid) {
document.getElementById("form-error").style.display = "inline-block";
return false; //to make the text appear
}
return true;
}
</script>
</head>
<body>
<form id="NewPatientForm" method="post" action="#" onsubmit="return validate();">
<div class="form-element">
<p id="form-error">All fields are required</p>
</div>
<div>
<label for="Firstname">First Name
<input type="text" name="Firstname" placeholder="First Name" id="Firstname">
</label>
</div>
<div>
<input type="submit" name="submit-button" value="Submit">
</div>
</form>
</body>
</html>
Looks like the culprit was your attempt to access Firstname on the document object.
I replaced it with the more standard document.getElementById() method and its working.
Some reading on this: Do DOM tree elements with ids become global variables?
function validate() {
var invalid = false;
if(!document.getElementById('Firstname').value.length) {
invalid = true;
}
if(invalid) {
document.getElementById("form-error").style.display = "inline-block";
return false;
}
return true;
}
#form-error {
display: none;
}
<form id="NewPatientForm" method="post" action="#" onsubmit="return validate()">
<div class="form-element">
<p id="form-error">All fields are required</p>
</div>
<div>
<label for="Firstname">First Name
<input type="text" name="Firstname" placeholder="First Name" id="Firstname">
</label>
</div>
<div>
<input type="submit" name="submit-button" value="Submit">
</div>
</form>
There are a couple of typos, and I'll suggest something else as well. First, a fix or three in the code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>NewPatientForm</title>
<script>
function validate() {
const invalid = document.getElementById("Firstname").value.length == 0;
if(invalid) {
document.getElementById("form-error").style.display = "inline-block";
return false; //to make the text appear
}
return true;
}
</script>
</head>
<body>
<form id="NewPatientForm" method="post" action="#" onsubmit="return validate();">
<div class="form-element">
<p id="form-error">All fields are required</p>
</div>
<div>
<label for="Firstname">First Name
<input type="text" name="Firstname" placeholder="First Name" id="Firstname">
</label>
</div>
<div>
<input type="submit" name="submit-button" value="Submit">
</div>
</form>
</body>
</html>
My suggestion is that you also look into built-in HTML form validation attributes. I'm thinking you're reinventing the wheel for things like requiring a non-empty Firstname. Why not this instead of JavaScript?
<input type="text" name="Firstname" id="Firstname" placeholder="First Name" required />
And many others, like minlength="", min="", step="", etc.
Plus there's still a JavaScript hook into the validation system with .checkValidity() so you can let the built-in validation do the heavy lifting, and then throw in more of your own custom aspects too.

Javascript | Simple Form Validation Wont Work

I have been working on this really simple login, where all i want to do is say, if the password is "apple" and password is "123" then link me to another page when i click submit button.
I gave up on the submit button linking portion but i still don't understand why my code won't register, everything looks right to me
<!DOCTYPE html>
<html>
<body>
<form name="loginForm">
<input type="text" name="username" placeholder="Username" value=""/>
<input type="password" name="password" placeholder="Password" value=""/>
<input type="button" name="submit" value="Login" onclick="validate()" />
</form>
<script type="text/javascript">
function validate() {
var user = document.loginForm.username.value;
return user;
var pass = document.loginForm.password.value;
return pass;
if ( (user=="apple") && (pass=="123") ) {
document.write("It worked");
} else {
document.write("Wrong Password");
}
}
</script>
</body>
</html>
Suggestions:
return keyword will exit the function, so the code after return won't be reached. To remove the two 'return' statement is the first step.
document.write will clear the page after document is loaded. You probably need alert function
try using document.getElementById/getElementByName (which is better) instead of document.loginForm...
It is also better to put onsubmit in the form tag (fired after type=submit button is clicked) instead of onclick event for button.
It is better to put Javascript inside the HTML head tag.
Below is a much better/working version:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validate() {
var user = document.getElementById("username").value;
var pass = document.getElementById("password").value;
if ( (user=="apple") && (pass=="123") ) {
alert("It worked");
return true;
} else {
alert("Wrong password");
return false;
}
}
</script>
</head>
<body>
<form action="" onsubmit='javascript:return validate()'>
<input type="text" id="username" placeholder="Username" value=""/>
<input type="password" id="password" placeholder="Password" value=""/>
<input type="submit" value="Login" />
</form>
</body>
</html>

How to make first pair of fields REQUIRED and others not?

I am using Ajax to submit forms in serial. I am trying to make the first s_referee_email + s_referee_fname pair required while the second or others not - there will be up to five of these pairs. I cant seem to figure how to make just the first pair required without breaking the form. I have tried using HTML5 and some answers from stack but havent been able to get anything to work. Any advice is greatly appreciated!
fiddle: https://jsfiddle.net/badsmell/gcrvqbna/
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<!--serial submit ajax-->
<script>
function mySubmit(){
var myForms = $("form");
myForms.each(function(index) {
var form = myForms.eq(index);
var serializedForm = form.serialize();
serializedForm += '&s_referer_fname='+$('#s_refererFname').val();
$.post("http://post.aspx", serializedForm, function (data, status) {
if (status === "success"){
window.location.href= "http://redirect";
}
});
});
}
</script>
<title>Forward a copy to a friend</title>
<style type="text/css">
*[class=hide] {
display: none
}
</style>
</head>
<body>
<!--hidden iframe-->
<iframe class="hide" id="myIframe"></iframe>
<form method="post" action="post.aspx" target="myIFrame">
<input type="hidden" name="s_referer_email" value="test#test.com" />
<input type="text" size="30" maxlength="255" name="s_referee_email" value="" required >
<input type="text" size="22" maxlength="50" name="s_referee_fname" value="" required >
</form>
<form method="post" action="post.aspx" target="myIFrame">
<input type="hidden" name="s_referer_email" value="test#test.com" />
<input type="text" size="30" maxlength="255" name="s_referee_email" value="" >
<input type="text" size="22" maxlength="50" name="s_referee_fname" value="" >
</form>
<label for="s_referer_fname">Your name:</label> <br /> <input type="text" name="s_referer_fname" value="" size="20" id="s_refererFname" ><br>
<p><button onclick="mySubmit();">Submit</button> </p>
</body>
</html>
Adding required="required" to the tags can let you make any field compulsory to be filled by user.
You should never use .onclick(), or similar attributes from a userscript.
Userscripts operate in a sandbox, and onclick operates in the target-page scope and cannot see any functions your script creates.
Always use addEventListener() (or an equivalent library function, like jQuery .on()).
So instead of code like:
something.outerHTML += '<input onclick="func()" id="button_id" ...>'
You would use:
something.outerHTML += '<input id="button_id" ...>'
document.getElementById ("button_id").addEventListener ("click", func, false);
And for your answer, one method is to perform a check before actually submitting the forms. Check if the required fields have been filled, if yes, go ahead and submit the form, or else don't submit and show an error message instead.

Javascript for form validation isn't functioning

defined the script in the head of my html file but still doesn't function is it because the action for my form leads to a php file?
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["food_name"].value;
if (x==null || x=="")
{
alert("Food name must be filled out");
return false;
}
</script>
<title> my title is going here </title>
</head>
<body>
<form name="myForm" action="http://xxxxxxxxx/~xxxxxxxx/file/phpfile.php" method="post" onsubmit="validateForm()">
<b>foodName:</b> <input type="text" name="food_name"><br>
<b>Food Type:</b> <input type="text" name="food_type"><br>
<b>Total:</b> <input type="text" name="total"><br>
<b>Available:</b> <input type="text" name="available"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Fix the missing curly braces } for the validateForm function and update onsubmit to this
onsubmit="return validateForm()"
other wise it will submit the form even if validation is failed
check http://jsfiddle.net/Thu69/
you have missing brace in your validateForm function

Implementing jQuery function

I have been trying to implement some JavaScript that would disable a submit button until all fields were filled. I found a great here: Disabling submit button until all fields have values. Hristo provided a link that does exactly what I need here: http://jsfiddle.net/qKG5F/641/.
My problem is that when I try to put together a full "minimum working example" I am completely stumped. I'm sure there's some minor aspect that I'm missing but here's what I've come up with:
<html>
<head>
<title></title>
<style type="text/css">
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled'); // updated according to https://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
} else {
$('#register').removeAttr('disabled'); // updated according to https://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
}
});
})()
</script>
</head>
<body>
<form>
Username<br />
<input type="text" id="user_input" name="username" /><br />
Password<br />
<input type="text" id="pass_input" name="password" /><br />
Confirm Password<br />
<input type="text" id="v_pass_input" name="v_password" /><br />
Email<br />
<input type="text" id="email" name="email" /><br />
<input type="submit" id="register" value="Register" disabled="disabled" />
</form>
<div id="test">
</div>
</body>
I simply copied/pasted and added in what I thought would be necessary to make the page work but my submit button remains permanently disabled. What simple part am I missing to make this work??
Thanks!
You have to surround it with an onload function:
$(window).load(function(){
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})()
});
If you look at the source of the jsFiddle, you'll see it got wrapped the same way.
I tested this on my system, works with your own version of jquery, as well as code with a little change and wrapping javascript in document.ready().
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
} else {
$('#register').removeAttr('disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
}
});
});
</script>
</head>
<body>
<form>
Username<br />
<input type="text" id="user_input" name="username" /><br />
Password<br />
<input type="text" id="pass_input" name="password" /><br />
Confirm Password<br />
<input type="text" id="v_pass_input" name="v_password" /><br />
Email<br />
<input type="text" id="email" name="email" /><br />
<input type="submit" id="register" value="Register" disabled="disabled" />
</form>
<div id="test">
</div>
</body>
</html>
Your original js is an immediately-invoked function expression. Here's a link explaining that pattern:
http://benalman.com/news/2010/11/immediately-invoked-function-expression/
You defined an anonymous function and then immediately called it. By the time your html page had loaded, the script had already run. As others correctly answered, you need to instead wait for all the DOM elements to load before executing the script.
While
$(window).load(function(){};
works, you should probably use the jQuery version of this:
$(document).ready(function(){ };
For one, it's the jQuery idiom, and for another, $(window).load fires at a later time, where as $(document).ready() fires as soon as all DOM elements are available; not as soon as all assets (possibly large) are loaded.
Source: window.onload vs $(document).ready()
If you place the JavaScript (the entire script element) at the end of the page, right before the closing body tag, it should work. This is because the JavaScript needs to be run after the DOM is built. By placing your script after the page is loaded (and then immediately invoking it as you are doing), the document will be ready and it should work.
Working example: http://jsfiddle.net/NgEHg/

Categories