How to run given javascript code given in the following example? - javascript

I am trying to run a javascript code but it is not running. I don't know why?
Here is the code sample:
Javascript:
<Script Language="text/Javascript">
function validateForm()
{
var x=document.forms["form1"]["Injection"].value;
var y=document.forms["form1"]["limit"].value;
if (x==null || x=="")
{
alert("Injection must be filled out");
return false;
}
if (y==null || y=="")
{
alert("Limit must be filled out");
return false;
}
return true;
}
</Script>
HTML:
<form name="form1" method="post" action="/OT_Stock/addnewinjection.jsp" onsubmit="return validateForm()">
<input type="text" name="Injection" maxlength="100" size="20" value="" style="textfield">
<input type="text" name="limit" maxlength="100" size="20" value="" style="textfield" >
<input type="submit" value="Add Name" class="buttonmain">
Please tell me where I am going wrong?

Remove the onclick from the button
Add onsubmit="return validateForm()" to the form element.
The crucial bit is the return keyword. Without it the form will always submit. With it, when the validateForm method returns false (invalid form) the form will not submit.
Edit: OP has updated his question with the above suggestions.

forma name is " form1", instead of it should be "form1".Don't use language in the script tag instead use type='text/javascript'.

Related

Html Form Unable to Validate Inputs using JavaScript

I am creating an application. The HTML file is like the following:
<!DOCTYPE html>
<html>
<body style="background-color: #ccc">
<script type="javascript">
function validateform(){
alert("Hello");
var firstnameErr="";
var valid = true;
var name = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (fname==null || fname=="") {
firstnameErr = "required";
valid = false;
} else if (!fname.value.match(types)) {
firstnameErr = "format error";
valid = false;
}
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">*
<script type="javascript">
document.write(firstnameErr);
</script>
</span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
When I click on the submit button, it straightaway redirects to "ViewList.php" without seeming to run validatefom(). I added the alert() to check whether the function is executing or not. I want my form to submit only when it meets the validation requirements, not when valid is false.
Besides Typo errors, The main problem that I found is your script is not get executed and your validateform() method is not available. It happened because your script tag type attribute is not correct <script type="javascript">
To make it work you need to change it to this
<script type="text/javascript">
And please change your validation method validateform() as it has too may typo.
What is wrong with the code is that the OP is validating the old-fashioned way with an HTML5 form. Prior to HTML5, you had to use JavaScript for front-end validation; now things are much simpler and easier, too. Of course, the OP would replace the value of the action in the following example with the desired URL.
Note: there were errors in the OP's code, but if you get rid of the JavaScript and code the HTML making sure to add the following to the text input:
required pattern="[a-zA-Z]+"
then the form validates. In other words, you don't have to work so hard when you use HTML5 for form validation :)
<form id="myform" name="myform" method="POST" action="https://www.example.com">
<label for="fname">Firstname</label>: <input name="fname" placeholder="First name" maxlength="20" required pattern="[a-zA-Z]+">
<input type="submit" name="submit" value="Submit">
</form>
For those who prefer to do things the old-fashioned way, see this revision of the OP's code. Note: it uses a minimum of variables, employs short-cuts for less verbosity, and is organized with functions. Also, it is kind to the user's hands, too.
The way you have done you will never be able to use document.write to output anything, use this, working for me:
<!DOCTYPE html>
<script>
function validateform(){
alert("Hello");
var valid = true;
var fname = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (fname==null || fname=="") {
firstnameErr = 'required';
valid = false;
} else if (!fname.match(types)) {
firstnameErr = 'format error';
valid = false;
}
document.getElementById('msg').innerHTML = firstnameErr;
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">* <label id='msg'></label> </span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
It looks you have a series of typo in your code,
try this
<!DOCTYPE html>
<html>
<body style="background-color: #ccc">
<script>
function validateform() {
var firstnameErr = "";
var valid = true;
var name = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (name == null || name == "") {
firstnameErr = "required";
valid = false;
} else if (!name.match(types)) {
firstnameErr = "format error";
valid = false;
}
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">*
<script>
document.write(firstnameErr);
</script>
</span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

How can I prevent a form action if my JavaScript functions have returned false?

I'm very inexperienced with programming so sorry if this is stupid question.
I'm creating a form which the user will be able to submit using a button. I have used script functions to decide whether they will return true or false, with the only condition being that the input boxes must be filled. Here is a simplified version of my JavaScript and HTML code, I've only included one of the input boxes. (My real code has six)
function validateEmail() {
var x = document.forms["myForm"]["email"].value;
if (x == null || x == "") {
alert("Email must be filled out");
return false;
}
else {
return true;
}
}
<form name="myForm"
onsubmit="validateEmail()" method="post" action="Different_Page.html">
<label for="email">Email Address:</label>
<input type="email" name="email">
<input type="submit" value="Submit">
</form>
The issue is that if the user does not type in their email and the function returns false, it still goes to the page I only want it to go to when it returns true. So in other words, I want it to do nothing and stay on this page, but ONLY when the script returns false. How do I accomplish this?
You have to return false from the onsubmit function and not just from a function that that function calls.
onsubmit="return validateEmail()"
That said, modern code would avoid intrinsic event attributes in favour of binding event handlers with JavaScript …
function validateEmail(evt) {
var x = this.elements.email.value;
if (x == "") {
alert("Email must be filled out");
evt.preventDefault();
}
}
document.getElementById('myForm').addEventListener("submit", validateEmail);
<form id="myForm" method="post" action="Different_Page.html">
<label for="email">Email Address:</label>
<input type="email" name="email">
<input type="submit" value="Submit">
</form>
… or forget JavaScript entirely and just use the validation features introduced in HTML 5.
<form method="post" action="Different_Page.html">
<label for="email">Email Address:</label>
<input type="email" name="email" required>
<input type="submit" value="Submit">
</form>

JavaScript link error

I am using JavaScript to validate email. The problem is, when the email ids don't match, then one alert button will come. Once I click the button it still takes me to the other page, instead of same page to correct my mail id.
HTML:
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button" onClick="validate()">
JavaScript:
function validate()
{
if(document.getElementById("email").value != document.getElementById("confirm_email").value)
alert("Email do no match");
}
You need to tell the submit button to not perform the submit
function validate()
{
if (document.getElementById("email").value!=document.getElementById("confirm_email").value) {
alert("Email do no match");
return false;
}
}
The problem is because You have taken button type=submit
Change input type='button'
<input type="button" name="submit" value="submit" class="button" onClick="validate()">
and submit form using javascript
document.getElementById("myForm").submit();
I case you want to validate only on submit then use
event.preventDefault();
and then validate but after successful validation you have to submit the form using js or jq. JS method is given above and jq method is:
$("form").submit();
You should add return false; in your if code block if you dont want the redirect.
Its the browser's default to refresh the page when the form is submitted. To prevent this refresh, add return false;.
Learn more: return | MDN
<html>
<head>
<script>
function validate(){
if(document.getElementById("email").value != document.getElementById("confirm_email").value){
alert("Email do no match");
return false;
}
}
</script>
</head>
<body>
<form action="formsubmit.php" method="post" onsubmit="return validate()">
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button">
</form>
</body>
</html>
Use the below javascript code, your html code is correct!
Well executing the JavaScript code in StackOverflow Script Runner won't run and occur erorrs. If input boxes with email and confirm_email id(s) are declared, this should work.
Hope it could help!
function validate(){
if(!document.querySelector("#email").value === document.querySelector("#confirm_email").value){
alert("Email do not match.");
}
}
/* In JavaScript, the ! keyword before the condition belongs to execute the statement if the given condition is false. */
It must prevent the form to get submitted if the validation is failed. so
return validate();
must be there. So if the validate function returns a false value then it will stop the form to be submitted. If the validate function return true then the submission will be done.
<form method='post' action='action.php'>
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button" onClick="return validate();">
</form>
<script>
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validate(){
if(!validateEmail(document.getElementById('email').value))
{
alert('Please enter a valid email');
email.focus();
return false;
}
else if(document.getElementById('email').value!=document.getElementById('confirm_email').value) {
alert('Email Mismatch');
confirm_email.focus();
return false;
}
return true;
}
</script>
Fix that and remove type=submit and use a function or use following code:
<script>
function check(){
//* Also add a id "submit" to submit button*//
document.querySelector("#submit").addEventListener("click", function(){
//* Perform your actions when that submit button will be clicked and close with this in next line*//
})</script>

JavaScript custom validation not working

Here is my code :
<script type="text/javascript">
function submitform() {
if(document.getElementById('name').value=='') {
alert('Please enter a name');
return false;
}
}
</script>
<form action="mail.php" method="post" onsubmit="submitform();">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
as expected, the form when submitted should call the submitform function, and if the name field is blank, it should return false and give an alert.
But, it just goes through.
Any explainations?
You need to call the function with return, so that the false value prevents default action (form submission)
<form action="mail.php" method="post" onsubmit="return submitform();">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
You need to stop a little.
You can use onSubmit, but it's best to delete your input submit and put a button.
Then on button click you can do what you want and eventually submit the form
Form:
<form action="mail.php" method="post" id="mailForm">
<input type="text" id="name" name="name" placeholder="name">
<button id="submitMailForm">Submit</button>
JS:
$( document ).on( "click", "#submitMailForm", function(e) {
//My control Here
//If all ok
$("#mailForm").submit();
});
You can use jquery instead of javascript for this kind of validation is will be very easy to implement.
<form action="mail.php" method="post">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit" id="submit">
</form>
<script>
$(document).ready(function(){
$("#submit").click(fucntion(e){
if($("#name").val() == ""){
alert("Name is empty");
e.preventDefault();
}
});
});
</script>
And dont forget to add jquery library before the script tag.
You need to change your onSubmit attribute as follows
onsubmit="return submitform();"
So your html look like this
<form action="mail.php" method="post" onsubmit="return submitform();">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
To cancel submission, the listener needs to return true or false. Also, if the function validates the fields, far better to name it for what it does rather than when it does it so call it something like "validateForm".
Also, giving a control a name of "name" masks the form's own name property. While that doesn't matter here, in general it's not a good idea to give any form control a name that is the same as a standard property of a form (e.g. "submit" or "reset").
So you might end up with something like:
<script>
function validateForm(form) {
if (form.personName.value == '') {
alert('Please enter a name');
return false;
}
}
</script>
<form ... onsubmit="return validateForm(this);">
<input type="text" name="personName">
<input type="submit">
</form>
<script type="text/javascript">
function submitform(event) {
if(document.getElementById('name').value=='') {
alert('Please enter a name');
event.preventDefault();
return false;
}
}
</script>
<form action="mail.php" method="post" onsubmit="submitform(event);">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
You need to prevent default of submit. In JS return false does not stop the propagation of the "submit" function (with frameworks can be different).
I suggest you to read:
event.preventDefault() vs. return falseenter link description here
just try this script
function submitform() {
var x = document.forms["fname"].value;
x = x.trim(); // Remove white spaces
if (x==null || x=="") {
alert("First name must be filled out");
return false;
}
}

Validate a form using JavaScript

I am a beginner and I have written a code for validating the form as:
function validateForm(){
var x=document.forms["myForm"]["fname"].value;
if (x==null || x==""){
alert("First name must be filled out");
return false;
}}
<!-- html part-->
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form><br>
The problem with this code is pressing submit button triggers the validateForm function. How to call the function when the object losses focus?
This is the exact solution to my problem. Where the user gets some kind of notification when the object losses focus:
<script>
function validate(){
var y = document.getElementById("errorResponse");
var x=document.forms["myForm"]["fname"].value;
if (x==null || x==""){
y.innerHTML = "Error";
}
}
</script>
The HTML form is:
<form name="myForm">
First name: <input type="text" name="fname" onBlur = "validate()">
<div id = "errorResponse"></div>
<input type="submit" value="Submit">
</form>
The div can be designed in CSS to red color to get user attention and many more tricks can be played.
replace your input element's code by following
<input type="text" onblur="return validateForm();" name="fname">
i guess thats what you are looking for
<html>
<head>
<script type="text/javascript">
function validateForm(oForm){
var els = oForm.elements;
for(var i = 0; i < els.length; i++){
if('string' === typeof(els[i].getAttribute('data-message'))){
return valEl(els[i]);
}
}
}
function valEl(el){
var method = el.getAttribute('data-valMethod');
if('req' === method && (el.value === null || el.value === '')){
alert(el.getAttribute('data-message'));
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="#" onsubmit="return validateForm(this)" method="post">
First name:
<input data-message="First name must be filled out" data-valMethod="req" onchange="return valEl(this)"; name="fname"><br />
<input type="submit" value="Submit">
</form>
</body>
</html>​​​​​​​​​​​​​​​​​​​
I have Split it in one function that can validate the elements on "onchange" and another one that fires the validations for each element on form.onsubmit(), if there's the required data-message attribute on a form element.
Since HTML5 the Data-* attributes are very handy for these things :-)
This way you can avoid having to store the name of the form and elements in the validation script, since you pass references to the elements themselfes instead. Which is always a good thing.
From here you can expand the valEl-function to accommodate other types of validation.
Only limitation so far is that there can be only one type of validation per element, but that should be easy enough to get around.
Happy coding.
/G
PS http://jsfiddle.net/ePPnn/11/ for sample code

Categories