im a bit new using javascript in HTML. I want to validate a HTML script using javascript however what i've written doesn't seem to work. Can anyone tell me where I'm going wrong???
Here is the Javascript:
<script type="text/javascript">
function mandatoryFields()
{
var x=document.forms["add"]["contract_id"].value
if (x==null || x=="")
{
alert("Please Enter the Contract Title");
return false;
}
var x=document.forms["add"]["storydiv"].value
if (x==null || x=="")
{
alert("Please Enter a Sprint");
return false;
}
var x=document.forms["add"]["storydiv"].value
if (x==null || x=="")
{
alert("Please Enter a Story");
return false
}
var x=document.forms["add"]["date1"].value
if ( x=="" || x==null)
{
alert("Please Enter a time");
return false
}
</script>
And here is the corresponding HTML script
<form name="add" action="time-sheet/insert-time-sheet.php" method="post" onsubmit="return mandatoryFields()">
<table width="500" border="0" align="center" cellpadding="2" cellspacing="2">
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td width="150">Select Date:</td>
<td width="336"><input name="date" type="text" value="YYYY-MM-DD" maxlength="100" class="datepick" id="date1" /></td>
</tr>
<tr>
<td>Contract:</td>
<td><SELECT NAME="contract_id" onChange="getSprint(this.value)"><OPTION VALUE=0>--- Select Contract ---<?php echo $options_contract?></SELECT></td>
</tr>
<tr>
<td>Sprint:</td>
<td><div id="sprintdiv"><select name="sprint" >
<option>--- Select Sprint ---</option>
</select></div></td>
</tr>
<tr>
<td>Story:</td>
<td><div id="storydiv"><select name="story">
<option>--- Select Story ---</option>
</select></div></td>
</tr>
<tr>
<td>Dev Time:</td>
<td><input name="dev_time" size="20" onkeyup="ondalikSayiKontrol(this)" /></td>
</tr>
<tr>
<td>PM Time:</td>
<td><input name="pm_time" size="20" onkeyup="ondalikSayiKontrol(this)"/></td>
</tr>
<tr>
<td colspan="2"><table width="182" border="0" align="center" cellpadding="2" cellspacing="2">
<tr>
<td width="68"><input name="Submit" type="submit" id="Submit" value="Add Time Sheet" /></td>
<td width="48"><label>
<input type="reset" name="reset" value="Reset" />
</label></td>
<td width="46"><div align="center">Back</div></td>
</tr>
<input type="hidden" name="day" value="<?php echo $day; ?>" />
<input type="hidden" name="employee_id" value="<?php echo $employee_id; ?>" />
</table></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
</table>
</form>
Thanks in advance!
You're missing the closing brace on the function. If you check the error console on your browser, it will most likely tell you mandatoryFields() is undefined. Adding the closing brace will fix that. You should also return true if none of the validation fails. One last thing is that you re-declare x before each if. Not sure if it produces an error but still should be fixed.
<script type="text/javascript">
function mandatoryFields()
{
var x=document.forms["add"]["contract_id"].value;
if (x==null || x=="")
{
alert("Please Enter the Contract Title");
return false;
}
x=document.forms["add"]["storydiv"].value;
if (x==null || x=="")
{
alert("Please Enter a Sprint");
return false;
}
x=document.forms["add"]["storydiv"].value;
if (x==null || x=="")
{
alert("Please Enter a Story");
return false;
}
x=document.forms["add"]["date1"].value;
if ( x=="" || x==null)
{
alert("Please Enter a time");
return false;
}
return true; // ADD THIS
} // ADD THIS
</script>
Your madatoryFields() function is not returning true when all fields are right.
from here:
If the event handler is called by the onsubmit attribute of the form
object, the code must explicitly request the return value using the
return function, and the event handler must provide an explicit return
value for each possible code path in the event handler function.
Get the right elements and perform a loop on the options inside of sprint and story.
You can use the name of your form and the names of your select boxes to access the elements straight forward.
var x = document.add.contract_id.value;
if(){
... your stuff here
}
You can also access the first form without using its name attribute.
x = document.forms[0].contract_id.value;
For sprint loop through possible options and make your alert then.
x = document.add.sprint;
var selected = false;
for (i = 0; i < x.length; ++i){
if (x.options[i].selected == true)
selected = true;
}
if(!selected){
alert("Select a story please!");
return false;
}
x = document.add.story;
selected = false;
// same procedure
You can also access the elements via getElementByID() and getElementsByTagName(), the latter returns an array of all matched elements.
document.getElementById('storydiv').getElementsByTagName('story')[0];
document.getElementsByTagName('contract_id')[0];
And dont redeclare var x in every validation step.
Related
I Cannot get the javascript to work! I need the Password and Re-Type Password fields, validate that both have values and that the user has entered the same password in both fields (i.e. password match) validate the password field must be more than 8 characters.I dont want to use the alert function instead, highlight the uncompleted fields with red background and a text message next to each uncompleted field (in red color) with the error message.
I have spent 3 days doing this!! any help appreciated.`
function validate() {
var fn =
document.getElementById("FName");
if (fn.value == "") {
{
document.getElementById("FName").style.borderColor = "red";
return false;
}
return true;
}
function validate() {
var sn =
document.getElementById("SName");
if (sn.value == "") {
document.getElementById("SName").style.borderColor = "red";
return false;
}
return true;
}
function validate() {
var un =
document.getElementById("UName");
if (un.value == "") {
document.getElementById("UName").style.borderColor = "red";
return false;
}
return true;
}
function checkPass() {
var pass = document.getElementById('pass');
var c_pass = document.getElementById(' c_pass')
var message = document.getElementById('confirmMessage');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if (pass.value == c_pass.value) {
c_pass.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
} else {
c_pass.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!"
}
return true;
}
}
<body>
<form action="Linkpage.html" id="myForm" method="post" name="myForm" onsubmit="return(validate())">
</form>
<br>
<table>
<tr>
<td align="center" colspan="2"><span style="font-size:50px; color:blue;">Registration form</span>
</td>
</tr>
<tr>
<td align="center" colspan="2">Welcome to our website
<br>please fill in <span style=" color:red;">all</span>
<b><ins>fields</ins></b>
</td>
</tr>
<tr>
<td>First Name</td>
<td>
<input autofocus="" id="FName" placeholder="Enter First name " type="text">
</td>
</tr>
<tr>
<td>Last Name</td>
<td>
<input id="SName" placeholder="Enter Last name " type="text">
</td>
</tr>
<tr>
<td>Username</td>
<td>
<input id="UName" placeholder="Enter username " type "text">
</td>
</tr>
<tr>
<td>Age</td>
<td>
<input id="Age" placeholder="Enter age" type="text">
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input id="pass" placeholder="Enter password " type="password">
</td>
</tr>
<tr>
<td>Confirm Password</td>
<td>
<input name="confirm password" id="c_pass" placeholder="Re-type your password " type="password" onkeyup="checkPass(); return false;">
<span id="confirmMessage" class="confirmMessage"></span>
</td>
</tr>
<tr>
<td rowspan="2">Gender</td>
<td>
<input name="mGender" type="radio" value="Male">Male</td>
</tr>
<tr>
<td>
<input name="fGender" type="radio" value="Female">Female</td>
</tr>
<tr>
<td>Available</td>
<td>
<input id="checkbox" type="checkbox">
</td>
</tr>
<tr>
<td>Course</td>
<td>
<select>
<option value="Mobile App">
Mobile App
</option>
<option value="Cloud">
Cloud
</option>
<option value="Software Development">
Software Development
</option>
</select>
</td>
</tr>
<tr>
<td class="Comments">Comments</td>
<td>
<br>
<textarea cols="30" name="Comments" placeholder="Type your comments here." rows="6"></textarea>
</td>
</tr>
<tr>
<td align="center" colspan="4" align="center">
<input name="submit" onclick="return validate()" type="submit" value="Register" align="center" />
</td>
</tr>
</table>
</body>
A couple of things here...
Get rid of the table, tr and td. You open a form and then you close it. Add all of your input fields in the form.
Then don't add three functions all called validate. Which one do you suppose is going to be called?
Rather change them to
function validateFname()
function validateSname()
function validateUname()
then
Use === and !=== instead of == and !=.
I think when you start clearing up your JavaScript and your HTML, things will start to make more sense.
Did you try to debug your code using Chrome's debugger or similar?
Each time you write the validate() function, you're overwriting the previous instance of it.
I recommend instead of using the same function name 3 times, write 2 different functions - matches() and required(), each with a different purpose.
matches(field1, field2){
return field1 == field2;
}
required(field){
return field != false;
}
Then you can pass into those functions the various fields you're validating.
There are a lot of bugs in your code and this is normal as a beginner its great to see you trying. So what I have done is took a look at your javascript. I am not going to re-write you whole script but I have commented out the part you should take a look at and try and comment one part at a time to see where you problem is. But I did get your match password working for you by commenting out your other stuff. Just try this for now. Then remove comments line by line until it stops working again. This will tell you how to find the other error's in your script.
<script>
function checkPass(){
var passValue = document.getElementById('pass').value;
var c_passValue = document.getElementById('c_pass').value;
var c_passID = document.getElementById('c_pass');
var message = document.getElementById('confirmMessage');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if(passValue == c_passValue) {
c_passID.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!";
} else {
c_passID.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!";
}
}
</script>
Okay so the issue was that you were attempting to change the color of the value of the c_pass and not the id itself. I renamed your variables to help you understand why it was breaking. Again this is only for the checkPass function. If you comment out all the other stuff and just use this script for now this will help you isolate the checkPass function and see that it works. I hope this helps.
I've made a couple of JavaScript function and I'm looking for the best way to implement them into my web application.
The main Three functions are:
Focus()
Focus does exactly what you think it will do, it gives focus to a textbox.
This has a check build in that checks which textfield needs the focus.
The function looks something like this:
function Focus(field) {
if (Locatie.value == "" && Bonregel == ""){
Locatie.focus();
}
else if (Locatie.value == "") {
Locatie.focus
}
else if (Bonregel.value == "") {
Bonregel.focus();
}
}
And I think that I need to call use that functions as soon as the page loads.
Send()
Send does also do what you expect it do to, it sends (submits) the data from the form. And that functions looks something like this:
function Send(keycode, locatie, bonregel) {
//Assign fields to variables
Form_Keycode = document.getElementById("form_keycode");
Form_Locatie = document.getElementById("form_locatie");
Form_Bonregel = document.getElementById("form_bonregel");
// Assign values to fields
Form_Keycode.value = keycode;
Form_Locatie.value = locatie;
Form_Bonregel.value = bonregel;
//submit data from myform
document.myform.submit();
}
Check
This is the last big function that needs to be included, Check checks if which key is pressed and then uses Send() to send the information. This looks something like this:
function Check() {
// check alle data vooor verzenden
// Keycode 13 -> ENTER
// Keycode 125 -> Green key on device
Locatie = document.getElementById("locatie").value;
Bonregel = document.getElementById("bonregel").value;
if (event.keyCode == 125) {
Send(125, locatie, bonregel);
}
else if (event.keyCode == 13) {
delay(Send(13,locatie,bonregel), "Send", 500);
}
else {
Focus();
}
}
Now on to the question:
What would be the most efficient way to implement these functions into my html, and which methods should be used? my html looks like this:
<legend>Test</legend><br />
<form name="myform" action="/" method="post">
<input type="hidden" id="form_locatie" name="locatie" />
<input type="hidden" id="form_bonregel" name="bonregel" />
<input type="hidden" id="form_keycode" name="keycode"/>
</form>
<table>
<tr>
<td>Locatie:</td>
<td><input type="text" id="locatie" onkeyup="CheckLocation()" value="{locatie}" /></td>
</tr>
<tr>
<td>Bonregel:</td>
<td><input type="text" id="bonregel" onkeyup="keyup(event)" /></td>
</tr>
<tr>
<td>Bonlijst:</td>
<td><textarea id="bonregelbox" readonly></textarea></td>
</tr>
<tr>
<td></td>
<td><input type="button" value="Velden Legen" id="reset" onclick="ClearFields()" /></td>
</tr>
</table>
I would not use a different form for a function which requires javascript. I would wrap the table with a form element, add validation on event on the input fields onchange="check(this)" and keep it simple.
<form name="myform" action="/" method="post" onsubmit='return validate();'>
<table>
<tr>
<td>Locatie:</td>
<td><input type="text" id="locatie" onchange="check(this)" value="{locatie}" /></td>
</tr>
<tr>
<td>Bonregel:</td>
<td><input type="text" id="bonregel" onchange="check(this)" /></td>
</tr>
<tr>
<td>Bonlijst:</td>
<td><textarea id="bonregelbox" readonly></textarea></td>
</tr>
<tr>
<td></td>
<td><input type="button" value="Velden Legen" id="reset" onclick="ClearFields()" /></td><!-- i do not understand this! -->
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
This avoid's unnecessary assignments of values and variable declarations
1) Focus(param1,param2)
function Focus(Locatie,Bonregel) {
if (Locatie.value == "" && Bonregel.value == ""){
Locatie.focus();
}
else if (Locatie.value == "") {
Locatie.focus
}
else if (Bonregel.value == "") {
Bonregel.focus();
}
}
2) Send(param1,param2,param3)
function Send(keycode, locatie, bonregel) {
//Assign value directly
document.getElementById("form_keycode").value = keycode;
document.getElementById("form_locatie").value=locatie;
document.getElementById("form_bonregel").value=bonregel;
//submit data from myform
document.myform.submit();
}
3) Check()
function Check() {
// check alle data vooor verzenden
// Keycode 13 -> ENTER
// Keycode 125 -> Green key on device
if (event.keyCode == 125) {
Send(125, document.getElementById("locatie").value, document.getElementById("bonregel").value);
}
else if (event.keyCode == 13) {
delay(Send(13,document.getElementById("locatie").value,document.getElementById("bonregel").value), "Send", 500);
}
else {
Focus(document.getElementById("locatie"),document.getElementById("bonregel"));
}
}
i want to show the error messages next to the input element and if there's no error messages then send the data to the server (clear data from form) so fire the function on submit
http://codepen.io/anon/pen/RPNpNw
the problem is the error messages showed and disappeared quickly (blink)
but when change the input type to button
http://codepen.io/anon/pen/EjaZqe
will work but the data will be still in form and not cleared as input type="submit" will do
<!DOCTYPE html>
<html>
<head>
<title> </title>
</head>
<body>
<form>
<table style="width:50%;">
<tr>
<td>first name</td>
<td><input type="text" id="txtfname" /></td>
<td><span id="error"></span></td>
</tr>
<tr>
<td>age</td>
<td><input type="number" id="txtage" onblur="checkAge(txtage)" /></td>
<td><span id="errorage"></span></td>
</tr>
<tr>
<td>user name</td>
<td><input type="text" id="txtuser" /></td>
<td><span id="erroruser"></span></td>
</tr>
<tr>
<td>country</td>
<td>
<select onselect="checkSelect(this)" id="slct">
<option selected="selected" value="default">select your country</option>
<option>egypt</option>
<option>usa</option>
</select>
</td>
<td><span id="errorslct"></span></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="register" onclick="allvalidate()" /></td>
</tr>
</table>
</form>
<script>
function allvalidate() {
validate();
checkAge(txtage);
checkuser(txtuser);
checkSelect(this);
}
function validate() {
var txtf = document.getElementById('txtfname');
if (txtf.value == 0 || txtf.value == null) {
document.getElementById('error').innerText = ('you must enter firstname');
document.getElementById('error').style.color = 'red';
txtf.focus();
return false;
}
else {
document.getElementById('error').innerText = ('');
//return true;
}
}
function checkAge(input) {
if (input.value < 18 || input.value > 70) {
document.getElementById('errorage').innerText = ('age must be from 18 :70');
document.getElementById('errorage').style.color = 'red';
return false;
}
else {
document.getElementById('errorage').innerText = ('');
return true;
}
}
function checkuser(input) {
var pattern = '^[a-zA-Z]+$';
if (input.value.match(pattern)) {
document.getElementById('erroruser').innerText = '';
return true;
}
else {
document.getElementById('erroruser').innerText = ('enter valid email');
document.getElementById('erroruser').style.color = 'red';
return false;
}
}
function checkSelect() {
var select=document.getElementById('slct')
if (select.value=='default') {
document.getElementById('errorslct').innerText = ('you must choose country');
document.getElementById('errorslct').style.color = 'red';
return false;
}
else {
document.getElementById('errorslct').innerText = '';
return true;
}
}
</script>
</body>
</html>
Change
<td><input type="submit" value="register" onclick="allvalidate()" /></td>
To:
<td><input type="submit" value="register" onclick="return allvalidate()" /></td>
Otherwise the boolean value is discarded. You also need to change allvalidate to actually return false if one of the validations fail:
function allvalidate() {
var validated = true;
if (!validate()) validated = false;
if (!checkAge(txtage)) validated = false;
if (!checkuser(txtuser)) validated = false;
if (!checkSelect(this)) validated = false;
return validated;
}
<tr>
<td></td>
<td><input type="submit" value="register" onclick="allvalidate()" /></td>
</tr>
well, I'm not expert but what I think is that data is not sending, you need to call the function on onsubmit event, instead of calling it on onclick event. It would send the data as well.
I am a Computing teacher trying to stay one step ahead of my pupils whom are working on a assessment to with validating web forms using HTML and JavaScript. So far, I have managed to do the following but can no longer move forward:
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+='You must enter your name';
document.ExamEntry.name.focus();
document.getElementById("name").style.color="#FF0000";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+=' You must enter the subject';
document.ExamEntry.subject.focus();
document.getElementById("subject").style.color="#FF0000";
result = false;
}
if (document.ExamEntry.examnumber.value=="") {
msg+=' You must enter the examination number';
document.ExamEntry.examnumber.focus();
document.getElementById("examnumber").style.color="#FF0000";
result = false;
}
if(document.getElementById("examnumber").value.length!=4)
{
msg+='You must have exactly 4 digits in the examination number textbox';
document.ExamEntry.examnumber.focus();
document.getElementById("examnumber").style.color="#FF0000"
result = false;
}
function checkRadio() {
var user_input = "";
var len = document.ExamEntry.entry.length;
var i;
for (i=0;i< len;i++) {
if (document.ExamEntry.entry[i].length.checked) {
user_input = document.ExamEntry.entry[i].value;
break;
}
}
if (msg==""){
return result;
}
else
{
alert(msg);
return result;
}
}
function resetForm()
{
document.getElementById('ExamEntry').reset();
document.getElementById("name").style.color="#000000";
document.getElementById("subject").style.color="#000000";
document.getElementById("examnumber").style.color="#000000";
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name='ExamEntry' method='post' action='success.html'>
<table width='50%' border='0'>
<tr>
<td id='name'>Name</td>
<td><input type='text' name='name' /></td>
</tr>
<tr>
<td id='subject'>Subject</td>
<td><input type='text' name='subject' /></td>
</tr>
<tr>
<td id='examnumber'>Examination Number</td>
<td><input type='text' name='examnumber'></td>
</tr>
<tr>
<td id='entry'>Level of Entry</td>
<td><input type='radio' name='entry' value='gcse'>GCSE<BR></td>
<td><input type='radio' name='entry' value='as'>AS<BR></td>
<td><input type='radio' name='entry' value='a2'>A2<BR></td>
</tr>
<tr>
<td><input type='submit' name='Submit' value='Submit' onclick='return (validateForm());'></td>
<td><input type='reset' name='Reset' value='Reset' onclick=' (resetForm());'></td>
</tr>
</table>
</form>
</body>
What I want to do and what I am trying to do are two different things and it's now hit the point where I am banging my head against a brick wall.
What I WANT to do is be able to:
Extend the Javascript code to make sure that the user’s examination number is exactly 4 digits.
Add a set of radio buttons to the form to accept a level of entry such as GCSE, AS or A2. Write a function that displays the level of entry to the user in an alert box so that the level can be confirmed or rejected.
Can anyone help me before I totally lose the plot?
It's been a long time I have tried pure JS. It's a pleasure to try it out anytime though. So, someone's lukcy and I had some free time. I am a very tiny bit OCD when it comes to coding and I ended up cleaning a lot of your code, such as
Always enclose HTML attributes in double quotes - not a hard rule though.
Always close the input attributes - /> - not a hard rule though.
Define your elements and resue where needed in JS
Alwayst try and keep your JS separate from HTML - it's a good practice.
And follow the good old basics
As a result, here we go:
Demo: Fiddle
HTML:
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="#">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="examnumber">Examination Number</td>
<td><input type="text" name="examnumber" /></td>
</tr>
<tr>
<td id="entry">Level of Entry</td>
<td><input type="radio" name="entry" value="gcse" />GCSE<BR></td>
<td><input type="radio" name="entry" value="as" />AS<BR></td>
<td><input type="radio" name="entry" value="a2" />A2<BR></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" /></td>
<td><input type="reset" name="Reset" value="Reset" onclick="resetForm();"></td>
</tr>
</table>
</form>
JS:
var form = document.forms['ExamEntry'];
var iName = form.elements['name'];
var iSubject = form.elements['subject'];
var iExamNumber = form.elements['examnumber'];
var iLevel = form.elements['entry'];
function validateForm() {
var result = true;
var msg = "";
if (iName.value=="") {
msg+='You must enter your name';
iName.focus();
iName.style.color="#FF0000";
result = false;
} else if (iSubject.value=="") {
msg+=' You must enter the subject';
iSubject.focus();
iSubject.style.color="#FF0000";
result = false;
} else if (iExamNumber.value=="" || !/^\d{4}$/.test(iExamNumber.value)) {
msg+=' You must enter a valid examination number';
iExamNumber.focus();
iExamNumber.style.color="#FF0000";
result = false;
} else if(!checkEntry()) {
msg+=' You must select a level';
result = false;
} else {
var cfm = confirm("You have selected " + checkEntry() + ". Are you sure to punish yourself?");
if (!cfm) {
result = false;
}
}
if (!result && msg != "") alert (msg);
return result;
}
function checkEntry() {
for (var i=0; i<iLevel.length; i++) {
if (iLevel[i].checked) {
return iLevel[i].value.toUpperCase();
}
}
return false;
}
function resetForm() {
form.reset();
iName.style.color="#000000";
iSubject.style.color="#000000";
iExamNumber.style.color="#000000";
}
form.onsubmit = validateForm;
form.onreset = resetForm;
First you added the function checkRadio inside of function validateForm
Also, this line
if(document.getElementById("examnumber").value.length!=4)
actually points to this piece of html
<td id='examnumber'>Examination Number</td>
The td element can't hold values... You need to change the line to this:
if (document.ExamEntry.examnumber.value.length!=4) {
This jsfiddle should help you out...
I have two forms inside my body:
<body>
<form method=post name="signin">
<table>
<theader>Sign In</theader>
<tr>
<td>Email:</td>
<td>
<input type=text length=25 maxlength=25 name=em id=em />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type=password length=15 maxlength=15 name=up id=up />
</td>
</tr>
<tr>
<td colspan=2>
<input type=button value="submit" />
</td>
</tr>
</table>
</form>
<br>
<br>
<br>
<br>
<form method=post name="register">
<table>
<theader>Don't have an account? Register, it's Free!</theader>
<tr>
<td>Email:</td>
<td>
<input type=text length=25 name=email id=email /><span id="nameerror"></span>
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type=password length=15 name=pass id=pass />
</td>
</tr>
<tr>
<td>Confirm Password:</td>
<td>
<input type=password length=15 name=cpass id=cpass /><span id="pwerror"></span>
</td>
</tr>
<tr>
<td>Account Type:</td>
<td>
<select id="seltype">
<option name=standard SELECTED>Standard</option>
<option name=admin>Administrator</option>
</td>
</tr>
<tr>
<td colspan=2>
<input type=button value="submit" onClick="JavaScript:validate();" />
</td>
</tr>
</table>
</form>
</body>
I would like to do the following:
For each form, validate to ensure it's filled in and also for the second form I want to validate that the two password matched. I have the following:
$( document ).ready(function() {
var t = document.getElementById("email").value;
var y = document.getElementById("seltype").value;
var k = document.getElementById("pass").value;
var j = document.getElementById("cpass").value;
$('#cpass').blur(function(){
if (k != j) {
document.getElementById("pwerror").innerHTML = "Password does not match";
}
else {
document.getElementById("pwerror").innerHTML = "Password matches";
}
});
});
function validate() {
if (t != null && y != null && k != null && j != null) {
}
if (t == "" || y == "" || k == "" || j == "") {
alert("fill in");
}
}
I preferred not to mix native JavaScript and validated using pure jQuery only. One of the benefits here is that the empty field check would work for any <form> since it's not tied to any particular form, input name or ids.
$( document ).ready(function() {
$( 'form' ).submit(function(event) {
var $form = $( this );
var checkPass = true;
$form.find( 'input' ).each(function( i, e) {
if (e.value.length === 0) {
event.preventDefault();
alert(e.name + " cannot be empty");
return (checkPass = false);
}
});
if( checkPass && $form.is( '[name="register"]' ) ) {
if( $form.find( '#pass').val() !== $form.find( '#cpass' ).val()) {
event.preventDefault();
alert( 'Passwords do not match.' );
}
}
});
});
Working Demo at JsFiddle.net
Basics:
If you want to check if a variable is not null, ideally, you should use !== & not !=.
If you want to check if a variable is "", ideally, you should use === and not ==.
Check out: http://www.w3schools.com/js/js_comparisons.asp
Use JSFiddle.net to give a better working example of your code WHICH can help others see a demo of your actual code.
Your code currently has lot of scope for optimization. Since its just a basic validation you are trying to achieve, why do you need to use jQuery? Why not just use JavaScript basic variable comparisons?
Google before you ask here. If its so straightforward, your question will get downvoted.
Alert is not the best way to notify the user to fill in. For example, your 'Password Matches' or 'Password Doesn't Match' div is a much better way to notify the user. Use Form Events to validate the form as the user is already filling in the details in the form!
Question responsibly by giving your exact problems and not just pasting the code! How would we know where you are facing a problem.
Variables work in Scope. Check the scope of variable before using them in different functions. For example, you define var t, y, k, j in first function and use it in second function - will throw up an error of undefined variable t.
From what information you provided, here's what I could help with:
HTML:
<form method=post name="signin">
<table>
<theader>Sign In</theader>
<tr>
<td>Email:</td>
<td>
<input type=text length=25 maxlength=25 name=em id=em />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type=password length=15 maxlength=15 name=up id=up />
</td>
</tr>
<tr>
<td colspan=2>
<input type=button value="submit" onclick="javascript:validateSignin()" />
</td>
</tr>
</table>
</form>
<br>
<br>
<br>
<br>
<form method=post name="register">
<table>
<theader>Don't have an account? Register, it's Free!</theader>
<tr>
<td>Email:</td>
<td>
<input type=text length=25 name=email id=email /><span id="nameerror"></span>
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type=password length=15 name=pass id=pass />
</td>
</tr>
<tr>
<td>Confirm Password:</td>
<td>
<input type=password length=15 name=cpass id=cpass /><span id="pwerror"></span>
</td>
</tr>
<tr>
<td>Account Type:</td>
<td>
<select id="seltype">
<option name=standard SELECTED>Standard</option>
<option name=admin>Administrator</option>
</td>
</tr>
<tr>
<td colspan=2>
<input type=button value="submit" onClick="JavaScript:validateRegister();" />
</td>
</tr>
</table>
</form>
JS:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function () {
$('#cpass').blur(function () {
if (k != j) {
document.getElementById("pwerror").innerHTML = "Password does not match";
} else {
document.getElementById("pwerror").innerHTML = "Password matches";
}
});
});
function validateRegister() {
var t = document.getElementById("email").value;
var y = document.getElementById("seltype").value;
var k = document.getElementById("pass").value;
var j = document.getElementById("cpass").value;
if (t !== null && y !== null && k !== null && j !== null) {}
if (t === "" || y === "" || k === "" || j === "") {
alert("fill in");
}
}
function validateSignin() {
var se= document.getElementById("em").value;
var sp= document.getElementById("up").value;
if (se !== null && sp !== null){ }
if (se === "" || sp === "") {
alert("fill in");
}
}
</script>
Hope it helps! :)