object oriented javascript form registeration - javascript

i am new to the object oriented javascript :)
i have written this code to validate the first name of a registration form, but it is not working
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>OOForm</title>
<meta name="author" content="engy" />
<!-- Date: 2015-02-20 -->
<script>
var Form = {
fname:{
minLength : 1,
maxLength : 15,
},
validateLength:function(formEl,type){
if(formEl.value.length>type.maxLength||formEl.value.length<type.minLength){
document.getElementById("firstNameSpan").innerHTML = "<font color='red'>Invalid User Name</font>";
return false;
}
else{
document.getElementById("firstNameSpan").innerHTML = "";
return true;
}
},
};
function checkForm(){
var ourForm = document.getElementById("ourForm");
var inputs = ourForm.getElementsByTagName("input");
if(Form.validateLength(inputs[0],Form.fname)){
document.getElementById("mySubmit").disabled = false;
return true;
}
document.getElementById("mySubmit").disabled = true;
return false;
}
</script>
</head>
<body>
<form id="ourForm">
<label>First Name</label>
<input type="text"/>
<span id="firstNameSpan"> </span>
<br/>
<input type="submit" value="submit" id="mySubmit" onclick="return checkForm()">
</form>
</body>
</html>
i don't know what is the problem with the code, but when i enter the firstname with invalid value and then press submit, it do nothing but clearing the text field
and the "invalid" span do not appear

I think it's because you need to do onsubmit on form element instead of onclick and you need to return false in onsubmit so browser won't try to send your form.

Related

Opening a local HTML page through javascript

I have this html code where the index.html loads first. It has a text field and a submit button. When the submit button is clicked, it calls the validateForm() function. Suppose the text field is empty, it should alert that it is empty, if it isn't then a new html page would load (either in new tab or current one) which is supposed to be welcome.html
So my problem is, the welcome.html file isn't loading. I even changed the "welcome.html" in window.location.href = "welcome.html" to "https://www.google.com" . The page still wouldn't load. What's wrong and what am I missing here ?
Any help is appreciated.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form</title>
<script src="/validateForm.js"></script>
</head>
<body>
<form method="get" onsubmit="return validateForm()">
Name: <input type="text" name="name" id="name">
<input type="submit" value="Submit">
</form>
</body>
</html>
validateForm.js
function validateForm() {
var name = document.getElementById("name");
var nameData = name.value;
if (nameData == "" || nameData == null) {
alert("Name must be filled!");
}
else {
window.location.href = "welcome.html";
}
}
welcome.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome :)</title>
</head>
<body>
<h1>Welcome!</h1>
</body>
</html>
Use action attribute
You can use the action attribute on the form to forward to a URL on success:
<form method="get" action="welcome.html" onsubmit="return validateForm()">
Name: <input type="text" name="name" id="name">
<input type="submit" value="Submit">
</form>
Documentation: MDN - Form action attribute
return value of validateForm()
See this?
onsubmit="return validateForm()"
Your validateForm doesn't return anything.
It is convention that return false means "stop processing the form" and a true-ish value means continue, which in turn means the action attribute mentioned above leads to welcome.html as you wanted.
The modified function could be this:
function validateForm() {
var name = document.getElementById("name");
var nameData = name.value;
if (nameData == "" || nameData == null) {
alert("Name must be filled!");
return false;
}
return true;
}
Alternatively, give validateForm a first parameter named event and call event.preventDefault() instead of returning false.
Documentation: MDN - Form submit handling example
You need some changes in index.html file and validateForm.js file
index.html
<form method="get" onsubmit="return validate()" action="javascript::window.location.replace('welcome.html')">
...
</form>
and in validateForm.js
you need to return true or false
after validation function if true it redirects to welcome.html or if false nothing were heppened.

Trying to learn to combine a form and script to affect my page

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<h1>placeholder</h1>
<form method="get">
<label for="word">enter word</label>
<input id="word" name="word" type="text" maxlength="15">
<input type="submit">
</form>
<script type="text/javascript">
let actualWord = document.getElementById('word');
if (actualWord === 'yes') {
document.querySelector('h1').innerHTML = "oh yeah";
} else {
document.querySelector('h1').innerHTML = "error";
}
</script>
</body>
</html>
Im very new to the world of coding and im hoping someone could help me with a "simple" test I was trying to perform.
I want this HTML code to replace the "Placeholder" text at the top of the screen with "oh Yeah" if the user types "yes" in the form.
Im hoping someone can tell me what im doing wrong or point me in the right direction.
https://github.com/Uken81/Form-test.git
1.You need to listen to form submit event and trigger a function
HTML
<form onsubmit="return handleSubmit()">...</form>
Javascript
function handleSubmit(evt) {
...
}
2.You get user's input value like this
document.getElementById('word').value
3.Also you need to prevent form from submitting, By returning false
Full Example
function handleSubmit(evt) {
let actualWord = document.getElementById('word').value;
if (actualWord === 'yes') {
document.querySelector('h1').innerHTML = "oh yeah";
}
return false;
}
<h1>placehold</h1>
<form onsubmit="return handleSubmit()">
<label for="word">enter word</label>
<input id="word" name="word" type="text" maxlength="15">
</form>
You can achieve that by adding click event listener to the <submit> button inside the form, and then perform the check on the text <input> and use .value attribute to get the <input> text value, note that I used [e.preventDefault()][3] to prevent the form from redirect, here is a working snippet:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<h1>placeholder</h1>
<form method="get">
<label for="word">enter word</label>
<input id="word" name="word" type="text" maxlength="15">
<input id="change-placeholder" type="submit">
</form>
<script type="text/javascript">
document.getElementById('change-placeholder').addEventListener('click', function(e){
e.preventDefault();
let actualWord = document.getElementById('word').value;
if (actualWord === 'yes') {
document.querySelector('h1').innerHTML = "oh yeah";
} else {
document.querySelector('h1').innerHTML = "error";
}
})
</script>
</body>
</html>

i want div content disappears after i click on textbox

<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<style>
#myloc,#mypass{
color: red;
}
</style>
<script>
function validateform(){
var username=document.login.username.value;
var password=document.login.password.value;
if (username==null || username==""){
var data="username should not be blank.";
document.getElementById("myloc").innerHTML=data;
return false;
}else if(password.length<6){
var p="Password must be at least 6 characters long.";
document.getElementById("mypass").innerHTML=p;
return false;
}
}
</script>
<body>
<form action="/loginusingservlet/LoginSES" onsubmit="return validateform()" method="post" name="login">
<table>
<tr>
<td>username</td><td> <input type="text" name="username"></td></tr>
<tr><td></td><td><div id="myloc"></div></td>
</tr><tr><td>password</td><td> <input type="text" name="password"></td></tr>
<tr><td></td><td><div id="mypass"></div></td></tr>
<tr><td></td><td><input type="submit" value="submit"></td></tr>
</table>
</form>
</body>
</html>
this program works great...when i click submit buttons it displays messages like "username should not be blank " or "password atleast 6".after getting message..if i click on a textbox i want the message disappear untill i click "submit" button.
Here you go. New function in script (it checks argument and removes text from specific element:
function removeWarning(type)
{
(type == 1) ? document.getElementById('myloc').innerHTML = "" : document.getElementById('mypass').innerHTML = "";
}
And add onClick event in inputs.
<input type="text" name="username" onClick="removeWarning(1)">
<input type="text" name="password" onClick="removeWarning(2)">
To me it is working but it was a quick solution, it is possible to improve a little.

JavaScript & DOM Logic Appears Correct but Won't Run Right

All I want to do is disable the button if there's no content in ftemp. If there is, I want the button to enable and check if it is numeric. Then I can send the ftemp to the next page. My html :
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function content()
{
var ftemp = document.getElementById("ftemp");
if (ftemp.value=="")
{
var convert = document.getElementById("convert").disabled=true;
document.getElementById("error").innerHTML = "";
}
else
{
isNumeric()
}
}
function isNumeric()
{
var ftemp = document.getElementById("ftemp");
if (isNaN(ftemp))
{
var convert = document.getElementById("convert").disabled=true;
document.getElementById("error").innerHTML = "Enter only numbers";
}
else
{
var convert = document.getElementById("convert").disabled=false;
document.getElementById("error").innerHTML = "";
}
}
</script>
</head>
<body onload="content()">
<form method="get" action="celsius">
<p>
<label>
Enter a temperature in Fahrenheit:
</label>
</p>
<p>
<input required id="ftemp" title="Enter only numbers!" size="3"
maxlength="3" onkeyup="content()"/>
<button id="convert" name="convert">Convert to Celsius</button>
</p>
<p id="error" name="error">
</p>
</form>
</body>
</html>
Inside isNumeric():
You are checking: isNaN(ftemp) where ftemp is a DOM element so it cannot be a number. Change to isNaN(parseInt(ftemp.value, 10)).
You have error here:
if (isNaN(ftemp))
Change it to:
if (isNaN(ftemp.value))
The ftemp is a DOM Object. You need to pass the value here.
Fiddle: http://jsbin.com/ocibuc/2

Show me a Simple javascript onSubmit handler

Hello again everyone
i am working on this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Form</title>
<script type="text/javascript">
</script>
</head>
<body>
<h2>**Form**</h2>
<form name=form method="post" action="javascript" subject=RSVP" enctype="text/plain" >
<input type=text name="first" size="20"> First Name<BR>
<input type=text name="last" size="20"> Last Name<BR>
<input type="text" name="email" size="20"> E-Mail<BR><BR>
<input type="submit" value="Submit">
<input type="reset" value="Clear Form"><br>
</form>
</body>
</html>
I am getting really confused here.. I need to have a onsubmit form handler and a create validation script. Ok now if I am right the validation script is the the function that needs to be placed right? sorry i know some of you guys might think this is easy but I am still learning. Now I have examples in my book of it but they only due one at a time. Is there a way you can do a onsubmit of all or does it have to be one at a time? thanks
ok I have this one i am working on..
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Form</title>
<script type="text/javascript">
<!--
function validate_form()
{
valid = true;
if ( document.contact_form.contact_first.value == "" )
{
alert ( "Please fill in the 'Your Name' box." );
valid = false;
}
return valid;
}
//-->
</script>
</head>
<body>
<h2>**Form**</h2>
<form name="contact_form" method="post" action="javascript" onSubmit="return validate_form();">
<input type=text name="contact_first" size="20"> First Name<BR>
<input type=text name="contact_last" size="20"> Last Name<BR>
<input type="text" name="contact_email" size="20"> E-Mail<BR><BR>
<input type="submit" value="Submit">
<input type="reset" value="Clear Form"><br>
</form>
</body>
</html>
now Can i just copy the function for the other two or how do i do the one for the email?
I've added an example here of how to do it:
http://jsfiddle.net/tomgrohl/JMkAP/
I added an onsubmit handler to the form:
<form method="post" action="javascript" enctype="text/plain" onsubmit="return valForm(this);">
And added this at the top of the page, a simple validation function:
<script type="text/javascript">
function valForm( form ){
var firstVal, lastVal, emailVal, error = '';
firstVal= form.first.value;
lastVal= form.last.value;
emailVal= form.email.value;
//OR
//firstVal= document.getElementById('first').value;
//lastVal= document.getElementById('last').value;
//emailVal= document.getElementById('email').value;
if( firstVal.length == 0){
error += 'First name is required\n';
}
if( lastVal.length == 0){
error += 'Last name is required\n';
}
if( emailVal.length == 0){
error += 'Email is required\n';
}
if( error ){
alert( error );
return false;
}
return true;
}
</script>
OnSubmit is invoked once for the form.
You can validate all the form fields in one onSubmit function, during one call to that function.
function myOnSubmitHandler(theForm) {
if (theForm.data1.value == "") {
alert("This field is empty.");
return false; // suppress form submission
} else {
return true; // A-OK, form will be submitted
}
}
in HTML:
<form method="POST" ACTION="SomethingOnServer.php"
onSubmit="return myOnSubmitHandler(this);">
I need to have a onsubmit form handler
You said it; <form onsubmit="return myValidate(this);" .... >
myValidate is your validation function that returns true|false indicating whether or not you want the form to be submitted to its handler script (which your also missing).
might I suggest you use jQuery and jQuery validate to validate your form no need to re-invent the wheel
be sure to check out validator's demo

Categories