I have the following html code:
<form name="Register" action="Register.aspx" method="post" runat="server" style="margin-top: 15px;" onsubmit="return validateProfile(FormName='Register');" >
<p>
Name* : <input id="FirstName" type="text" name="FirstName"/> </p>
<input type="submit">
</form>
And this JS code:
function isEmpty(field) {
return (field == "" || field == null)
}
function validateProfile(FormName) {
var Fname = document.forms[FormName]["FirstName"].value; return false;
var g = (isEmpty(field));
alert(g);
}
The problem is in this line :
var Fname = document.forms[FormName]["FirstName"].value; return
false;
I get this error message :
uncaught typeerror cannot read property 'FirstName' of undefined
If I write instead of the line above this line
document.getElementById("FirstName").value
It works great, so my question is why document.forms[FormName]["FirstName"].value does not work?
document.forms[FormName]["FirstName"] will try to access a property on a javascript HTMLFormElement forms object. The [Id] syntax can only be used on a collection. To access an element with the id FirstName use document.forms[FormName].elements['FirstName'].value
document.forms[name] returns the element, not a mapping input name => value. This would work :
var Fname = document.forms[FormName].getElementsByTagName('Input')[5].value;
return false;
Your validation function has some problem
I don't know why you are using
return false;
after
var Fname = document.forms[FormName]["FirstName"].value;
Try this
function validateProfile(FormName) {
var Fname = document.forms[FormName]["FirstName"].value;
var g = (isEmpty(Fname));
alert(g);
}
I don't know what problem you are facing exactly so I am attaching the complete working cope of the code and tested on chrome and IE as below
<!DOCTYPE html>
<html>
<body>
<form name="Register" action="Register.aspx" method="post" runat="server" style="margin-top: 15px;" onsubmit="return validateProfile('Register');" >
<p>
Name* : <input id="FirstName" type="text" name="FirstName"/> </p>
<input type="submit">
</form>
<script language="javascript">
document.write(document.forms[0].name);
function isEmpty(field) {
return (field == "" || field == null)
}
function validateProfile(formname) {
var Fname = document.forms[formname]["FirstName"].value;
var g = (isEmpty(Fname ));
alert(g);
return false;
}
</script>
</body>
</html>
Related
I am trying to get an html form to grab a value from a javascript code. I'd like for the hidden field "SubID" to grab the value of the javascript function. This is what I have so far.. what am I doing wrong:
<form action="" method="post">
<fieldset><input name="firstname" type="text" placeholder="First Name" /></fieldset>
<input type="hidden" name="SubID" value="uid1">
<fieldset><button id="contact-submit" name="submit" type="submit" data-submit="...Sending">Submit</button></fieldset>
<script type="text/javascript">
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
var uid1 = document.write(getCookie("uid"));
</script>
Add a listener to the submit event of the form:
// declare listener
function handleSubmit() {
var myHiddenInput = document.querySelector('[name=SubID]');
myHiddenInput.value = getCookie("uid");
}
// hook listener to the event of the form
var myForm = document.querySelector('form');
myForm.addEventListener("submit", handleSubmit, false);
That should work in the latest browsers. If you need to support older browsers, the .addEventListener() changes a little.
More on how to add simple event listeners here.
Demo in JSBin or below:
function getCookie(name) {
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
//var uid1 = document.write(getCookie("uid"));
var myForm = document.querySelector('form');
function handleSubmit() {
var myHiddenInput = document.querySelector('[name=SubID]');
// myHiddenInput.value = getCookie("uid");
myHiddenInput.value = "test -- have a look at the network tab to check if this was submitted";
}
myForm.addEventListener("submit", handleSubmit, false);
<form action="https://httpbin.org/post" method="post">
<fieldset><input name="firstname" type="text" placeholder="First Name" /></fieldset>
<input type="hidden" name="SubID" value="uid1">
<fieldset>
<button id="contact-submit" name="submit" type="submit" data-submit="...Sending">Submit</button>
</fieldset>
</form>
I am just practicing js. I am trying to make a very simple validation in form but it came with, as i was expecting, an error.
Here's my code :
var form = document.getElementById('form');
var name = document.getElementById('name');
var email = document.getElementById('email');
var msg = document.getElementById('message');
var error = document.getElementById('error');
function handlingForm() {
form.onsubmit = function(c)
{
if (name.value == "")
{
error.innerHTML = "Error Submiting Form !";
return false;
}
else
{
error.innerHTML = "You have successfuly submited the Form..! Congrats ;)";
return true; // ;) Just Kidding :D
}
};
}
window.onload = function(c)
{
handlingForm();
}
<!DOCTYPE html>
<html>
<head>
<title>jsForm</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="container">
<form id="form">
<input type="text" placeholder="Name" id="name">
<input type="text" placeholder="Email" id="email">
<textarea rows="4" placeholder="Message" id="message"></textarea>
<input type="submit" value="Send" id="send">
<p id="error"></p>
</form>
</div>
<script src="script.js"></script>
</body>
</html>
The problem is that, it doesn't validate it. Every time it returns true on submitting but when i replace the " name.value" with "email.value" the code works. I don't know now what's the problem actually. If someone could help me..
It looks like the input with id name is not created in DOM by the time of JavaScript execution.
You can resolve that by putting the code in the window.onload code block or inside the form.onsubmit
var form = document.getElementById('form');
var email = document.getElementById('email');
var msg = document.getElementById('message');
var error = document.getElementById('error');
function handlingForm() {
form.onsubmit = function(c) {
var name = document.getElementById('name');
if (name.value == "") {
error.innerHTML = "Error Submiting Form !";
return false;
} else {
error.innerHTML = "You have successfuly submited the Form..! Congrats ;)";
return true; // ;) Just Kidding :D
}
};
};
handlingForm();
<div id="container">
<form id="form">
<input type="text" placeholder="Name" id="name">
<input type="text" placeholder="Email" id="email">
<textarea rows="4" placeholder="Message" id="message"></textarea>
<input type="submit" value="Send" id="send">
<p id="error"></p>
</form>
</div>
Your variable called name is a problem. It's not working because name is a predefined identifier in some implementations. Though it's not a reserved keyword, it's best practice to avoid using it as a variable name.
Rename it to name_ (or almost anything else) and it will work.
If name.value has no value, it is undefined. So undefined !== "", which is why it will never be true. Just do a null check for name.value. Also, you need to move name inside of that function since the first time it is called, value will always be undefined:
var form = document.getElementById('form');
var email = document.getElementById('email');
var msg = document.getElementById('message');
var error = document.getElementById('error');
function handlingForm() {
form.onsubmit = function(c)
{
var name = document.getElementById('name');
if (!name.value)
{
error.innerHTML = "Error Submiting Form !";
return false;
}
else
{
error.innerHTML = "You have successfuly submited the Form..! Congrats ;)";
return true; // ;) Just Kidding :D
}
};
}
window.onload = function(c)
{
handlingForm();
}
<!DOCTYPE html>
<html>
<head>
<title>jsForm</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="container">
<form id="form">
<input type="text" placeholder="Name" id="name">
<input type="text" placeholder="Email" id="email">
<textarea rows="4" placeholder="Message" id="message"></textarea>
<input type="submit" value="Send" id="send">
<p id="error"></p>
</form>
</div>
<script src="script.js"></script>
</body>
</html>
Try this:
window.onload = handlingForm();
Why your function has c parameter?
This is due to a quirk of how global variables are handled in web pages. Each one is treated as a property of the window object, so when you assign to email, you're actually creating and assigning to window.email, and so on.
However, some properties of the window object already exist and have special meaning to the browser, such as window.location (the current URL) and window.name (used in cross-frame link targets).
To see it in practice, do this in the global scope (outside any function):
var location; // should be undefined, right?
alert(location); // but it's actually window.location
Because of the special meaning of window.name, anything you assign to it (or to global name) will be converted into a string. The element that you try to store becomes a string, and so no longer works as an element.
To fix it, simply move your code into a function, so that the variables are local and no longer have this strange behaviour. You can use your window.onload function for this.
I am validating the dates in below function. If the validation fails, then the form should not get submitted. I tried returning false in form onsubmit but it still gets submitted. However, Validation is working fine and getting the alert that I put in the function. Any help to stop submitting the form if validation fails.
<script>
function dateCheck()
{
start = document.getElementById('name3').value;
end = document.getElementById('name4').value;
compare(start, end);
document.getElementById('name4').focus();
}
function compare(sDate, eDate)
{
function parseDate(input) {
var parts = input.match(/(\d+)/g);
return new Date(parts[2], parts[0]-1, parts[1]); // months are 0-based
}
var parse_sDate = parseDate(sDate);
var parse_eDate = parseDate(eDate);
parse_sDate.setFullYear(parse_sDate.getFullYear() + 1);
if(parse_eDate >= parse_sDate)
{
alert("End date should not be greater than one year from start date");
return false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit="return dateCheck()">
<table>
<tr>
<td><input type="text" name="soname3" id="name3" size="15" readonly="readonly">
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name3','MMddyyyy','dropdown',false,'12')" /></td>
<td><input type="text" name="soname4" id="name4" size="15" readonly="readonly">
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name4','MMddyyyy','dropdown',false,'12'); " /> </td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
Just a comment:
If your listener passes a reference to the form, you can access the controls by name or ID:
<form onsubmit="return dateCheck(this)">
then:
function dateCheck(form) {
var start = form.name3.value;
...
}
Note that you should declare variables, otherwise they will become global at the point they are assigned to. Also, you should check the values in the controls before passing them to the compare function (and display a message asking the user to enter a valid value if they aren't).
function dateCheck(form) {
var start = form.name3.value;
var end = form.name4.value;
var valid = compare(start, end);
if (!valid) form.name4.focus();
return false;
}
I appreciate all contributions above. I have just applied the suggestions above to solve my challenge & it works fine. Keeping it simple I use the following:
<form id="newuser" action="newuser.php" onsubmit="return pswderr(this)">
For the button I have
<input id='submit' type="submit" value="Login" onClick="return pswderr();">
My script is:
<script>
function pswderr() {
var pswd1 = document.getElementById("newuserpswd").value;
var pswd2 = document.getElementById("rptpswd").value;
if (pswd1 !== pswd2) {
document.getElementById("alarm").innerHTML = "Password and password
verification do not match. Retry";
return false;
} else {document.getElementById("alarm").innerHTML = "";
return true;
}
}
</script>
use return on the onclick attribute in the form tag attribute onsubmit="return validateForm()" , if you return false in your validation function in javascript if the input is incorrect then you have to add return to your onclick attribute in order for it to execute .Hope it helped someone!
<script>
function validateForm(){
var validation = false;
var phonenumber = document.forms["enqueryForm"]["phonenumber"].value;
if(phonenumber != 11) {
alert("phonenumber is incorrect");
//e.preventDefault();
return false;
}
}
</script>
<form class="form-style-5" action="BookingForm.php" method="post" id="bookingForm" onsubmit="return validateForm()" name="enqueryForm">
<input type="tel" name="phonenumber" placeholder="your no.">
<input type="submit" name="submit" value="submit">
</form>
return is not going to stop the form from submit if its called in a subfunction e.g. compare(sDate, eDate)
so change your function to this
function dateCheck(e){
var start = document.getElementById('name3').value;
var end = document.getElementById('name4').value;
if(compare(start, end)) {
// no error submit i guess
// return true ?
} else {
// error with date compare
return false;
}
end.focus();
}
In my case i used pattern in input field and also gave maxlength.
What worked with me was, remove Length attribute from input field
you can achieve the same thing using jQuery Form Plugin.
$(document).ready(function() {
$('#your_form_id').ajaxForm( { beforeSubmit: dateCheck } );
});
- I hope this will help you : Just write this code on your Html/jsp page
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
- **Don't forget to add this on your html page**
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function() {
//option A
$("regF").submit(function(e) { //regF is form id
alert('submit intercepted');
e.preventDefault(e);
});
});
</script>
</html>
Here is my code:
<input type="text" id="fname">
<input type="button" onclick = "b();" value="change" />
<script>
function b(){
var fanme = document.getElementById('fname');
if(fname.value){
fname.value="";
}else{
fname.value="ffff";
}
</script>
I tried this, but the fname's value sometimes changed when I click the button twice. What's the matter?
On other browsers is OK
Try this : instead of Elements use Element and also close function with }.
function b(){
var fanme = document.getElementById('fname');
if(fname.value){
fname.value="";
}else{
fname.value="ffff";
}
}
Try this,
<input type="text" id="fname">
<input type="button" onclick = "b();" value="change" />
<script>
function b(){
var fanme = document.getElementById('fname').value;
if(fname == "" || fname == null || fname == "null"){
fanme = "Set the value as you want";
}else{
//proceed
}
</script>
Please i just started learning javascript, In order to build my skill. I gave myself a javascript project to build an object validator.The first method i created is checkEmpty. This method check for empty field. But for reason unknow to me the method don't work.
This is the html form
<form name="myForm">
<input type="text" class="required email" name='fName'/>
<input type="text" class="required number" name="lName"/>
<input type="submit" value="submit" name="submit" id="submit"/>
</form>
This is the javascript that called the validator object
window.onload = function(){
var validate = new FormValidator('myForm');
var submit = document.getElementById('submit');
//this method won't work for internet explorer
submit.addEventListener('click',function(){return checkLogic();},false);
var checkLogic = function(){
validate.checkEmpty('fName');
};
}
This is the javascript object called Formvalidation
function FormValidator(myForm){
//check ur error in stack overflow;
this.myForm = document.myForm;
this.error = '';
if(typeof this.myForm === 'undefined'){
alert('u did not give the form name ');
return;
}
}
//this method will check wheather a field is empty or not
FormValidator.prototype.checkEmpty = function(oEmpty){
var oEmpty = this.myForm.oEmpty;
if(oEmpty.value === '' || oEmpty.value.length === 0){
this.error += "Please Enter a valid Error Message \n";
}
FormValidator.printError(this.error);
};
This method printout the error;
FormValidator.printError = function(oData){
alert(oData);
};
After formatting your code it got a lot easier to find out what went wrong. I assume you are trying to validate the input fields from your html code.
Your code is falling on its nose the first time in line 1 of the method checkEmpty():
FormValidator.prototype.checkEmpty = function(oEmpty){
var oEmpty = this.myForm.oEmpty;
if(oEmpty.value === '' || oEmpty.value.length === 0){
this.error += "Please Enter a valid Error Message \n";
}
FormValidator.printError(this.error);
};
In the first line you are hiding the methods argument oEmpty with the var oEmpty statement from line 1
There are several other issues like overusing methods and members. The following code is probably what you wanted:
1.) index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<form name="myForm">
<input id="fName" name='fName' type="text"/>
<input id="lName" name="lName" type="text"/>
<input id="submit" name="submit" type="submit" value="submit"/>
</form>
<script src="main.js"></script>
</body>
</html>
2.) main.js
function InputFieldValidator(inputFieldName){
this.inputFieldName = inputFieldName;
this.inputField = document.getElementById(this.inputFieldName);
if(this.inputField === 'undefined'){
alert('No input field: ' + this.inputFieldName);
}
}
InputFieldValidator.prototype.validate = function(){
if(this.inputField.value === ''){
alert('Please enter valid text for input field: ' + this.inputFieldName);
}
};
window.onload = function(){
var fNameValidator = new InputFieldValidator('fName'),
lNameValidator = new InputFieldValidator('lName'),
submitButton = document.getElementById('submit');
submitButton.addEventListener('click', function (){
fNameValidator.validate();
lNameValidator.validate();
});
};
If you like you can wrap the input field validators from above easily in a form validator.
This is the right way to define functions this way:
var FormValidator = function(myForm){ /* function body */ };
FormValidator.prototype.checkEmpty = function(oEmpty){ /* function body */ };
Than, after instantiating the object, you can call FormValidator.checkEmpty(value) like you did.