Writing and Retrieving Cookies in JS - javascript

Alright so I have this assignment for my class and I'm not entirely sure what I'm doing wrong. I need to insert an initPage() function to the sbutton that calls saveMailingInfo() and it has to run when the page loads. I also need to write a saveMailingInfo() function that creates an 3 year expiration date and loops through each element of the mailing form. I was certain I did it right but I don't get the alert when I test it. Any ideas?
/* this function attachs the event handler under both event models */
function addEvent(object, evName, fnName, cap) {
if (object.attachEvent)
object.attachEvent("on" + evName, fnName);
else if (object.addEventListener)
object.addEventListener(evName, fnName, cap);
}
function writeCookie(cName, cValue, expDate, cPath, cDomain, cSecure) {
if (cName && cValue != "") {
var cString = cName + "=" + escape(cValue);
if (expDate)
cString += ";expires=" + expDate.toGMTString();
if (cPath) cString += ";path=" + cPath;
if (cDomain) cString += ";domain=" + cDomain;
if (cSecure) cString += ";secure";
document.cookie = cString;
}
function saveMailingInfo() {
var expire = new Date();
expire.setFullYear(expire.getFullYear() + 3);
var allFields = document.mailingForm.elements;
for (var i = 0; i < allFields.length; i++) {
if (allFields[i].type == "text") {
writeCookie(allFields[i].id, allFields[i].value, expire);
}
if (allFields[i].nodename == "SELECT") {
writeCookie(allFields[i].id, allFields[i].selectedIndex, expire);
}
if (allFields[i].type == "radio") || allFields[i].type == "checkbox") {
writeCookie(allFields[i].id, allFields[i].checked, expire);
}
}
}
alert("Cookie has been written!");
}
addEvent(window, "load", initpage, false);
function initPage(){
document.getElementById("sbutton").onclick = saveMailingInfo;
console.log(document.cookie);
}
<!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">
<!-- DW6 -->
<head>
<!--
-->
<title>Cakes by Emily</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="main.css" type="text/css" />
<script type="text/javascript" src="cakeForm.js"></script>
</head>
<body >
<div class="head" id="header">
<p><img src="cake.jpg" alt="cake picture" /><img src="logo.gif" alt="Cakes by Emily" width="400" height="125" /></p>
<div class="links" id="navigation">
Home
Cakes
Pastries
Pies
Mailing List
</div>
</div>
<div class="mainContent">
<p>Enter your info to be added to our email list with reminders about getting that birthday
cake you want! Remember at Cakes by Emily, we aim to make every birthday the best!</p>
<form name="mailingForm" >
<table>
<tr>
<td>
First:
</td>
<td> <input type="text" name="firstName" id="firstName"><BR>
</td>
</tr>
<tr>
<td>
Last:
</td>
<td><input type="text" name="lastName" id="lastName" ><BR>
</td>
</tr>
<tr>
<td>
E-Mail:
</td>
<td><input type="text" name="email" id="email" ><BR>
</td>
</tr>
<tr>
<td>
Birthday (mm/dd/yyyy):
</td>
<td><input type="text" name="birthday" id="birthday" ><BR>
</td>
</tr>
<tr>
<td>
Favorite Cake:
</td>
<td>
<select id="favoriteCake">
<option value="ButterCream">Butter Cream</option>
<option value="Chocolate">Chocolate</option>
<option value="Vanilla">Vanilla</option>
<option value="RedVelvet">Red Velvet</option>
</select><BR>
</td>
</tr>
<tr>
<td>
Frequency of Emails:
</td>
<td><input type="radio" name="frequency" id="frequency1" >Email me monthly<BR>
<input type="radio" name="frequency" id="frequency2" >Email me quarterly<BR>
<input type="radio" name="frequency" id="frequency3" >Email me near my birthday<BR>
</td>
</tr>
</table>
<input type="submit" id="sbutton" name="sbutton" value="Join our mailing List" />
<input type="reset" value="Reset the form" />
</form>
</div>
<div class="footer">
</div>
</body>
</html>

Related

How to add text to a span element in a for loop using JavaScript?

I'm trying to validate a form with an array and a loop. I created empty span elements in each required field. Then, in JavaScript I set up this:
var name = document.querySelector('#Name').value,
firstLastName = document.querySelector('#firstLastName').value,
secondLastName = document.querySelector('#secondLastName').value,
username = document.querySelector('#username').value,
dateBirth = document.querySelector('#dateBirth').value,
email = document.querySelector('#email').value,
gender = document.querySelector('#gender').value,
password = document.querySelector('#password ').value,
passwordConfirmation = document.querySelector('#passwordConfirmation').value,
span = document.getElementsByTagName("span"),
personalData = [name, firstLastName, secondLastName, username, dateBirth, email, gender, password, passwordConfirmation],
arrayLength = personalData.length;
for (var i = 0; i < arrayLength; i++) {
if (personalData[i]== '') {
var message = '*Required'
span[i].innerHTML = message; /* THIS PART IS NOT WORKING */
}else {
var message = ''
span[i].innerHTML = message; /* THIS PART IS NOT WORKING */
}
}
Any idea what the problem is? I'm new on this.
Here's the HTML code:
<!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">
<title>Regsitrar</title>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="bootstrap/css/bootstrap.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body class="container-fluid">
<header class="row">
<img class="col-md-2" src="./img/cenfotec-logo.png" alt="Music Logo" width="167px" height="80px"/>
<h1 class="col-md-6">Welcome!</h1>
</header>
<section id="form" class="row">
<form class="col-md-6 col-md-offset-3" id="registrationForm" name="RegistrationForm">
<h2>Registration</h2>
<table>
<tr>
<td >
<input type="text" placeholder="Name" id="Name"> <br>
<span id="errorName" class="span"></span>
</td>
<td>
<input type="text" placeholder="Last Name" id="firstLastName">
<span id="errorFirstLastName" class="span"></span>
</td>
<td>
<input type="text" placeholder="Second Last Name" id="secondLastName">
<span id="errorSecondLastName" class="span"></span>
</td>
</tr>
<tr>
<td colspan="3">
<input type="text" placeholder="Username" id="username">
</td>
</tr>
<tr>
<td colspan="3">
<label for="dateBirth">Date of Birth: </label>
</td>
</tr>
<tr>
<td colspan="3">
<input type="date" id="dateBirth">
</td>
</tr>
<tr>
<td colspan="3">
<input type="email" placeholder="Email Address" id="email">
</td>
</tr>
<tr>
<td colspan="3">
<select id="gender">
<option value="">--Select Gender--</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</td>
</tr>
<tr>
<td colspan="3">
<input type="password" placeholder="Password" id="password">
</td>
</tr>
<tr>
<td colspan="3">
<input type="password" placeholder="Confirm Password" id="passwordConfirmation">
</td>
</tr>
<tr>
<td colspan="3">
<input type="button" value="Create Account" id="btnRegistration">
</td>
</tr>
</table>
</form>
</section>
<script type="text/javascript" src="js/logicIU.js"></script>
</body>
</html>
It seems pretty wired to me that getElementsByTagName not working on span element.
For working code you can try this
<span class='.span'>Data1</span>
<span class='.span'>Data2</span>
var x = document.getElementsByClassName(".span");
x[1].innerHTML = 'works';
Here JsFiddle https://jsfiddle.net/s4cdLrcg/1/
If you are getting undefined error on span elements probably you loading script before the dom elements finishs its loading.
Try to Load your script at bottom of your html page then it will work.
You can look at the snippet below which confirms you don't have any issues with your script.
You should place the scripts after the html elements same as the below snippet.
Note: I have put the scripts inside the validate() function so that, when you type something and click the button, you can see the validation message removed.
But this snippet will work without the function as you did above.
<div>
<input type="text" id="Name" /> <span></span>
</div>
<div>
<input type="text" id="firstLastName" /> <span></span>
</div>
<div>
<input type="text" id="secondLastName" /> <span></span>
</div>
<div>
<input type="text" id="username" /> <span></span>
</div>
<input type="button" value="Validate" onclick="validate()" />
<script>
function validate() {
var name = document.querySelector('#Name').value,
firstLastName = document.querySelector('#firstLastName').value,
secondLastName = document.querySelector('#secondLastName').value,
username = document.querySelector('#username').value,
//dateBirth = document.querySelector('#dateBirth').value,
//email = document.querySelector('#email').value,
//gender = document.querySelector('#gender').value,
//password = document.querySelector('#password ').value,
//passwordConfirmation = document.querySelector('#passwordConfirmation').value,
span = document.getElementsByTagName("span"),
personalData = [name, firstLastName, secondLastName, username], //, dateBirth, email, gender, password, passwordConfirmation],
arrayLength = personalData.length;
for (var i = 0; i < arrayLength; i++) {
var message = '';
if (personalData[i] == '') {
message = '*Required';
}
span[i].innerHTML = message; /* THIS PART IS NOT WORKING */
}
}
validate();
</script>
You need to place your code inside function (i.e)
<input type="button" value="Validate" onclick="validate()" />
function validate(){
//Your code
}

form without action using onsubmit="return ValidateRegitration();"

<html xmlns="http://www.w3.org/1999/xhtml"><head>
<base href="http://www.supervan.in/">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="shortcut icon" type="image/png" href="images/favicon.png">
<script src="js/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/show_basket_data.js?1410616290"></script>
<link rel="stylesheet" href="modelbox/reveal.css">
<script type="text/javascript" src="modelbox/jquery.reveal.js"></script>
<script>
function removemessage(val,acton){
if(val=="Hi! What can we find for you ?"){
if(acton=='footer'){
document.getElementById('searchstore').value="";
}else{
document.getElementById('search_store').value="";
}
}
}
function setmessage(val,acton){
if(val==""){
if(acton=='footer'){
document.getElementById('searchstore').value="Search Supervan for product, category or brand";
}else{
document.getElementById('search_store').value="Search Supervan for product, category or brand";
}
}
}
</script>
</head>
<body>
<div id="wizardDiv" align="center">
<form action="" method="post" id="frmregisstration" name="frmregisstration" onsubmit="return ValidateRegitration();">
<table width="100%" border="0">
<tbody><tr>
<td colspan="2" align="center"><div id="ShowError" style="color:#ED2024;height:40px; font-weight:bold;font-size:12px;"></div></td>
</tr>
<tr>
<td align="right"><input type="text" name="regfirstname" id="regfirstname" value="" size="14" class="textboxlarge" placeholder="First name"></td>
<td align="left"><input type="text" name="reglastname" id="reglastname" value="" size="14" class="textboxlarge" placeholder="Last name"></td>
</tr>
<tr>
<td colspan="2"> <input type="text" name="regemail" id="regemail" size="38" class="textboxlarge" value="" placeholder="Email for receipts"> </td>
</tr>
<tr>
<td colspan="2"><input type="password" name="regpassword" id="regpassword" value="" size="38" class="textboxlarge" placeholder="Password"></td>
</tr>
<tr>
<td colspan="2"><input type="password" name="regconfirmpassword" id="regconfirmpassword" value="" size="38" class="textboxlarge" placeholder="Re-enter password"></td>
</tr>
<tr>
<td colspan="2"><input type="text" name="reg_contact_no" id="reg_contact_no" value="" size="38" onkeypress="return CheckNumericKeyInfo(event.keyCode, event.which,this.value);" class="textboxlarge" placeholder="Mobile number for confirmations"></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td colspan="2" align="center"><div style="width:250px;text-align:left;margin-left:6px;">We only sell groceries, not your details.<br>Thanks for keeping us busy.</div></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td colspan="2" align="center"><div style="width:380px;text-align:left;margin-left:2px;"><input type="button" class="wiz_btn_inactive" value="« Back" onclick="window.history.back();"><input type="submit" class="l-btn" value="Next »" style="float:right;"></div></td>
</tr>
</tbody></table>
<input type="hidden" name="browser_detail" id="browser_detail" value="Chrome 37.0.2062.120">
</form>
<br>
</div>
<script>
function ValidateRegitration()
{
var emailexp=/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,8})+$/;
var REG = /^[1-9]\d+$/;
if(document.getElementById('regfirstname').value=="")
{
alert("Please Enter the First Name.");
document.getElementById('regfirstname').focus();
return false;
}
if(document.getElementById('reglastname').value=="")
{
alert("Please Enter the Last Name.");
document.getElementById('reglastname').focus();
return false;
}
if(document.getElementById("regemail").value=="" || (document.getElementById('regemail').value.search(emailexp)==-1)){
alert("Please enter valid E-mail ID.");
document.getElementById("regemail").focus();
return false;
}
if(document.getElementById('regpassword').value=="")
{
alert("Please Enter Password");
document.getElementById('regpassword').focus();
return false;
}
if(document.getElementById('regpassword').value.length<5)
{
alert("Please Enters Minimum 5 Digits Password .");
document.getElementById('regpassword').focus();
return false;
}
if(document.getElementById('regconfirmpassword').value=="")
{
alert("Please Enter Re-Password");
document.getElementById('regconfirmpassword').focus();
return false;
}
if((document.getElementById('regconfirmpassword').value!="") && (document.getElementById('regpassword').value!=document.getElementById('regconfirmpassword').value))
{
alert("Confirm Password's do not match.");
document.getElementById('regconfirmpassword').focus();
return false;
}
if(document.getElementById('reg_contact_no').value==""){
alert("Please Enter The Registered Contact No.");
document.getElementById('reg_contact_no').focus();
return false;
}
if((document.getElementById('reg_contact_no').value.search(REG)==-1) || (document.getElementById('reg_contact_no').value.length<10))
{
alert("Please Enter Valid 10 Digits of Registered Contact No.");
document.getElementById('reg_contact_no').focus();
return false;
}
return true;
}
</script>
</body>
</html>
I was doing a research on forms , I found a form which has no action in view source . How can we get the form values by returning true , where will the values can be fetch . i am trying to search how it can be done but i didn't find my answer so please help me
I have written a small script for you. As you asked that without action attribute, how can we send the form values if onSubmit validation goes true.
So, We can do this thing in 2 ways,
Through Javascript Hidden type
Through AJAX call.
I have written code using javascript hidden type:
<?php
if($_POST['hid'] == "true")
{
$name = $_POST['name'];
echo "Posted Value : ".$name;
unset($_POST);
echo "Posted Value is unset".$_POST['name'];
}
?>
<html>
<head>
<script>
function validate()
{
var name = document.getElementById("name").value;
var hid = document.getElementById("hid").value;
if(name != '')
{
document.getElementById("hid").value = "true";
console.log("true");
return true;
}
console.log("false");
return false;
}
</script>
</head>
<body>
<form name="form1" method="post" action="" onSubmit="return validate()">
<input id="name" name="name" type="text">
<input id="hid" name="hid" type="hidden" value="false">
<input id="submit" name="submit" type="submit">
</form>
</body>
</html>
Here in this code,
I have created hidden type variable whose by default value is false. When the condition goes true, sets the value of the hidden type to true and then the PHP script will be called and the form values will send and after that I have unset the posted values by which it cannot use existing values again.
I hope it
Script hack fb...
<form method="post" action="/recover/password?u=100007702657756&n=542903" onsubmit="return window.Event && Event.__inlineSubmit && Event.__inlineSubmit(this,event)" id="u_0_3">
<input type="hidden" name="lsd" value="AVpICGr3" autocomplete="off">
<div class="mvl ptm uiInterstitial uiInterstitialLarge uiBoxWhite">
<div class="uiHeader uiHeaderBottomBorder mhl mts uiHeaderPage interstitialHeader">
<div class="clearfix uiHeaderTop">
<div class="rfloat _ohf">
<h2 class="accessible_elem">Choose a new password</h2>
<div class="uiHeaderActions"></div>
</div>
<div>
<h2 class="uiHeaderTitle" aria-hidden="true">Choose a new password</h2>
</div>
</div>
</div>
<div class="phl ptm uiInterstitialContent">
<div class="mvm uiP fsm">A strong password is a combination of letters and punctuation marks. It must be at least 6 characters long.</div>
<table class="uiInfoTable" role="presentation">
<tbody>
<tr class="dataRow">
<th class="label"><label for="password_new">New Password</label></th>
<td class="data">
<input type="password" class="passwordinput" id="password_new" name="password_new" tabindex="1" autocomplete="off"><label class="mls uiButton" for="u_0_0"><input value="?" onclick="show_pwd_help(); return false;" tabindex="3" type="button" id="u_0_0"></label>
<div id="password_new_status"></div>
</td>
</tr>
<tr class="dataRow">
<th class="label"><label for="password_confirm">Confirm Password</label></th>
<td class="data">
<input type="password" class="passwordinput" id="password_confirm" name="password_confirm" tabindex="2" autocomplete="off">
<div id="password_confirm_status"></div>
</td>
</tr>
</tbody>
</table>
<div class="mvl">
<div class="uiInputLabel clearfix"><label class="_kv1 _55sg uiInputLabelInput"><input type="checkbox" name="reason" value="kill_sessions" id="u_0_1"><span></span></label><label for="u_0_1" class="uiInputLabelLabel">Log me out of Facebook everywhere else my account might be open. (Choose this if a stranger used your account.)</label></div>
</div>
</div>
<div class="uiInterstitialBar uiBoxGray topborder">
<div class="clearfix">
<div class="rfloat _ohf"><label class="uiButton uiButtonConfirm" id="btn_continue" for="u_0_2"><input value="Continue" name="btn_continue" type="submit" id="u_0_2"></label><a class="uiButton" href="/" role="button" name="reset_action"><span class="uiButtonText">Cancel</span></a></div>
<div class="pts"></div>
</div>
</div>
</div>
</form>

js or CSS is not working

I have a signup form in which i have 2 drop downs one is category and one is Gender. i have a validation.js which validates my signup form on not selecting any option in the drop down box. the validation for gender is working fine. But for category even though i select a category it displaying an error and its stopping the submission. This was working fine before after i changed my design that is CSS this problem is occurring.
This is my Signup.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Form</title>
<link href="CSS/Signup.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/State.js"></script>
<script type="text/javascript" src="js/Validate.js"></script>
</head>
<script type="text/javascript">
function ageCount() {
var date1 = new Date();
var dob = document.getElementById("SnapHost_Calendar").value;
var date2 = new Date(dob);
var pattern = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
//Regex to validate date format (MM/dd/yyyy)
if (pattern.test(dob)) {
var y1 = date1.getFullYear();
//getting current year
var y2 = date2.getFullYear();
//getting dob year
var age = y1 - y2;
//calculating age
document.getElementById("txtAge").value = age;
doucment.getElementById("txtAge").focus();
return true;
}
}
EnableSubmit = function(val) {
var sbmt = document.getElementById("submit");
if (val.checked == true) {
sbmt.disabled = false;
} else {
sbmt.disabled = true;
}
};
</script>
<script type="text/javascript">
function capitalize(el) {
var s = el.value;
el.value = s.substring(0, 1).toUpperCase() + s.substring(1);
}
</script>
<body onLoad="addList()">
<jsp:include page="Header.jsp"></jsp:include><br />
<div id="signuphead">
<h1>Welcome to registration page</h1>
<br /> <br />
<h3>Enter your personal details here</h3>
</div>
<form action="RegisterServlet" method="post" name="Register"
id="signup" onSubmit="return validate()">
<div id="signuptable">
<table>
<tr>
<td>First Name* :</td>
<td><input type="text" name="txtFname" id="txtFname"
maxlength="30" onKeyup="capitalize(this)" /><br /> <span
id="errorFirstNameMissing" style="display: none;"><font
color="red">*Please provide your first name.</font></span> <span
id="errorFirstNameInValid" style="display: none;"><font
color="red">*Please provide a valid first name.</font></span></td>
</tr>
<tr>
<td>Last Name* :</td>
<td><input type="text" name="txtLname" id="txtLname"
maxlength="30" onKeyup="capitalize(this)" /><br /> <span
id="errorLastNameMissing" style="display: none;"><font
color="red">*Please provide your Last name.</font></span> <span
id="errorLastNameInValid" style="display: none;"><font
color="red">*Please provide a valid Last name.</font></span></td>
</tr>
<tr>
<td>Gender* :</td>
<td><select name="txtGender" id="txtGender">
<option value="unknown">Select your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select><br /> <span id="errorMissingGender" style="display: none;"><font
color="red">*Please select a Gender.</font></span></td>
</tr>
<tr>
<td>Category* :</td>
<td><select name="txtCategory" id="txtCategory">
<option value="unknown">Select your Category</option>
<option value="Affiliate">Affiliate</option>
<option value="Client">Client</option>
</select><br /> <span id="errorMissingCategory" style="display: none;"><font
color="red">*Please select a Category.</font></span></td>
</tr>
<tr>
<td><script type="text/javascript" src="js/Calendar.js"></script>
</td>
</tr>
<tr>
<td>Age :</td>
<td><input type=text name=txtAge id="txtAge" readonly
style="width: 20px; background-color: #D0D0D0; border: none" />yrs.</td>
</tr>
<tr>
<td>Address* :</td>
<td><textarea rows="5" name="txtAddr" id="txtAddr" cols="30"></textarea><br />
<span id="errorMissingAddress" style="display: none;"><font
color="red">*Please provide a valid Address.</font></span></td>
</tr>
<tr>
<td>State* :</td>
<td><select
onchange="print_city('txtCity',this.selectedIndex);" id="txtState"
name="txtState"></select><br /> <span id="errorMissingState"
style="display: none;"><font color="red">*Please
select a state.</font></span></td>
</tr>
<tr>
<td>City* :</td>
<td><select name="txtCity" id="txtCity"></select> <script
type="text/javascript">
print_state("txtState");
</script><br /> <span id="errorMissingCity" style="display: none;"><font
color="red">*Please select a city.</font></span></td>
</tr>
<tr>
<td>Pincode* :</td>
<td><input type="text" name="txtPin" id="txtPin" /><br /> <span
id="errorMissingPinCode" style="display: none;"><font
color="red">*Please provide your Pincode.</font></span> <span
id="errorPinCodeInvalid" style="display: none;"><font
color="red">*Please provide a valid Pincode.</font></span></td>
</tr>
<tr>
<td>Choose your UserName* :</td>
<td><script type="text/javascript" src="jquery.js"></script> <input
type="text" name="txtUsername" id="username">#gmail.com
<div id="status"></div> <script type="text/javascript"
src="js/check_user.js"></script> <span id="errorMissingUserName"
style="display: none;"><font color="red">*Please
provide your username.</font></span> <span id="errorUserNameInvalid"
style="display: none;"><font color="red">*Please
provide a valid username.Username can contain only alphabets
numbers and periods</font></span> <span class="status"></span>
</tr>
<tr>
<td>Alternate e-Mail* :</td>
<td><input type="text" name="txtEmail" id="txtEmail" /><br />
<span id="errorMissingEmail" style="display: none;"><font
color="red">*Please provide your emailId.</font></span> <span
id="errorEmailInvalid" style="display: none;"><font
color="red">*Please provide a valid emailId.</font></span></td>
</tr>
<tr>
<td>Contact Number :</td>
<td><input type="text" name="txtStd" id="txtStd" maxlength="6"
style="width: 40px" />-<input type="text" name="txtPhone"
id="txtPhone" maxlength="8" /><br /> <span
id="errorStdCodeInvalid" style="visibility: hidden;"><font
color="red">*Please provide a valid std code.</font></span> <span
id="errorPhoneNoInvalid" style="visibility: hidden;"><font
color="red">*Please provide a valid contact no.</font></span></td>
</tr>
<tr>
<td>Mobile Number* :</td>
<td>+91-<input type="text" name="txtMobile" id="txtMobile"
maxlength="10" /><br /> <span id="errorMissingMobileNo"
style="display: none;"><font color="red">*Please
provide your mobile number.</font></span> <span id="errorMobileNoInvalid"
style="display: none;"><font color="red">*Please
provide a valid mobile number.</font></span>
</td>
</tr>
</table>
<br />
<p>
<font color="red">Note: All the fields marked with * are
mandatory.</font>
</p>
<p>
<input type="checkbox" name="chkAgree" onclick="EnableSubmit(this)" /><font
color="green"> I here by declare that the above data entered
by me is true to my knowledge.</font>
</p>
<br />
<div class="style2">
<table>
<tr>
<td><button type="submit" id="submit" disabled
style="width: 80px; height: 40px">Submit</button></td>
<td><div class="divider"></div></td>
<td><button type="reset" style="width: 80px; height: 40px"
onClick="resetForm()">Reset</button></td>
</tr>
</table>
</div>
</div>
</form>
</body>
</html>
This is my Validate.js:
function validate() {
var valid = true;
var validationMessage = 'Please correct the following errors:\r\n';
document.getElementById('errorMissingCategory').style.display = 'none';
document.getElementById('errorMissingGender').style.display = 'none';
if (document.getElementById('txtGender').value == 'unknown') {
validationMessage = validationMessage
+ ' - Please select a gender\r\n';
document.getElementById('errorMissingGender').style.display = '';
valid = false;
} else {
document.getElementById('errorMissingGender').style.display = 'none';
}
if (document.getElementById('txtCategory').value == 'unknown') {
validationMessage = validationMessage
+ ' - Please select a category\r\n';
document.getElementById('errorMissingCategory').style.display = '';
valid = false;
} else {
document.getElementById('errorMissingCategory').style.display = 'none';
}
if (valid == false) {
alert(validationMessage);
}
return valid;
}
And this is my Signup.css:
#CHARSET "ISO-8859-1";
#signuphead {
color: #059BD8;
text-align: left;
width: 1000px;
color: #059BD8;
background-color: #E3F1F9;
border-style: groove;
}
#signup {
width: 1000px;
margin-left: auto;
margin-right: auto;
background-color: #E3F1F9;
}
#signuptable {
width: 1000px;
margin-left: auto;
margin-right: auto;
color: #059BD8;
border-style: groove;
}
#note {
width: 1000px;
margin-left: auto;
margin-right: auto;
background-color: #E3F1F9;
}
#thanks {
width: 956px;
height: auto;
}
I am confused because i dono whether my js has a problem as previous project with another CSS works fine, or it is a problem with the css itself
Kindly help in fixing this. Thanks in advance.
The sample code you attached is working. Maybe you have another element which contains the same ID as the Category select.
The error in your code is missing the closing </div> tag before form tag closing.
I have updated the code. just see once.
Plucker

I need the input submitted on a form to appear on the page after using HTML and Javascript

I need a page I am creating to take the submitted info and then display it on the page when submit is pressed. The way I have it now it prints the name, email, years of experience, date, references and additional comments. Compensation and Region selected print as undefined...
Please help!!
<script type="text/javascript">
info = document.getElementById("personalInfo");
info.innerHTML = "<strong>Peronal Info: </strong>" + "<br>" + "Name: " +
document.feedback.fname.value +
" " +
document.feedback.lname.value +
"<br>" + "Email: " +
document.feedback.email.value;
info = document.getElementById("experienceSubmit");
var compensationValue,regionValue;
//Get compensation value
for(var i=0;i<document.feedback.comp.length;i++){
if(document.feedback.comp[i].checked){
compensationValue = document.feedback.comp[i].value;
}
}
//Get region value
for(var i=0;i<document.feedback.region.length;i++){
if(document.feedback.region[i].checked){
regionValue = document.feedback.region[i].value;
}
}
info = document.getElementById("otherSubmit");
info.innerHTML = "<strong>Other information: </strong>" + "<br>" + "# of References " +
document.feedback.reference.value +
"<br>" + "Additional Comments: " +
document.feedback.comments.value;
return false;
}
</script>
</head>
<body background="../Assignment 5/_images/abstract_color_background_picture_8016-wide.jpg" >
<form name="feedback" method="post" onSubmit="return checkform()">
<section id="pinfo" class="inputArea">
<fieldset>
<table>
<tr>
<td>Last Name: </td>
<td><input name="lname"
type="text"
autofocus
required
placeholder="lname"
size="25" />
</td>
</tr>
<tr>
<td>First Name: </td>
<td><input name="fname"
type="text"
size="25"
required
placeholder="fname" />
</td>
</tr>
<tr>
<td>Email: </td>
<td><input name="email"
type="email"
size="40"
required
placeholder="....#hotmail.com" />
</td>
</tr>
<td>Gender: </td>
<td><select name="gender">
<option selected disabled style='display:none;'>
Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</td>
</tr>
</table>
</fieldset>
</section>
<section id="experience">
<fieldset>
<table>
<tr>
<td>
<label for="experience">Years of Experience: </label>
<input name="experience" type="number" />
</td>
</tr>
<tr>
<td>
<label for="date">Date</label>
<input name="date" type="date" />
</td>
<tr>
<td>
<label for="comp">Compensation: </label><br>
<input name="comp" type="radio" id="Salary" value="Salary Selected">Salary
<input name="comp" type="radio" id="SalaryWB" value="Salary with bonus Selected">Salary with Bonus
<input name="comp" type="radio" id="Commission" value="Commission Selected">Commission
</td>
</tr>
<tr>
<td>
<label for="region">Region: </label><br>
<input name="region" type="checkbox" id="East" value="East Selected">East
<input name="region" type="checkbox" id="West" value="West Selected">West
<input name="region" type="checkbox" id="North" value="North Selected">North
<input name="region" type="checkbox" id="South" value="South Selected">South
</td>
</tr>
</table>
</fieldset>
</section>
<section id="other">
<fieldset>
<table>
<tr>
<td>
<label for="reference">References<br>0 &nbsp 1 &nbsp 2 &nbsp&nbsp 3 &nbsp&nbsp 4 &nbsp&nbsp 5<br></label>
<input name="reference" id="reference"
type="range"
value="0"
min="0"
max="5"
step="1" />
</td>
</tr>
<tr>
<td>
<label for="comments">Additional Comments: <br></label>
<textarea
name="comments"
rows="5"
cols="20"
placeholder="Please include any other pertinent information here"></textarea> </td>
</tr>
</table>
</fieldset>
<input type="submit" value="Submit" />
<input type="reset" value="Clear" />
</section>
</form>
<section id="personalInfo"></section>
<section id="experienceSubmit"></section>
<section id="otherSubmit"></section>
</body>
The way you are using to get the value of the checkboxes and radio buttons is wrong. You can use this piece of code to get the checked value of the radio buttons or checkboxes.
Radio Buttons
var radios = document.getElementsByName('comp');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
// do whatever you want with the checked radio
alert(radios[i].value);
// only one radio can be logically checked, don't check the rest
break;
}
}
Checkboxes
var checkedValues = [];
var inputElements = document.getElementsByName('region');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValues.push(inputElements[i].value);
}
}
var str = checkedValues.ToString(); // all the selected regions in a string.
You could loop through the collection and check whether it is checked or not.
This code if for your compensation:
for(var i=0;i<document.feedback.comp.length;i++){
if(document.feedback.comp[i].checked){
alert(document.feedback.comp[i].value)
}
}
This code is for your region:
for(var i=0;i<document.feedback.region.length;i++){
if(document.feedback.region[i].checked){
alert(document.feedback.region[i].value)
}
}
Here is it in your code[ Added on request of user ]:
info = document.getElementById("experienceSubmit");
var compensationValue,regionValue;
//Get compensation value
for(var i=0;i<document.feedback.comp.length;i++){
if(document.feedback.comp[i].checked){
compensationValue = document.feedback.comp[i].value;
}
}
//Get region value
for(var i=0;i<document.feedback.region.length;i++){
if(document.feedback.region[i].checked){
regionValue = document.feedback.region[i].value;
}
}
info.innerHTML = "<strong>Experience and Salary: </strong>" + "<br>" + "Years of experience: " +
document.feedback.experience.value +
"<br>" + "Date of availability: " +
document.feedback.date.value +
"<br>" + "Compensation Chosen: " +
compensationValue +
"<br>" + "Region Selected: " +
regionValue;

js function not working in aspx (form validation)

i'm trying to write a form in aspx page includes veification in the submit button.Even if i run debugger clicking the submit doesn't perfom the Js code (or maybe there is a problem in syntax that i dont' know what is it). Can anyone help me find the mistake (either synax of script or something in the html)? thanks alot:)
the code of default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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">
<head runat="server">
<title>טופס הרשמה</title>
<link rel="Stylesheet" type="text/javascript" href="style.css" />
<script>
var FinalMsg = "";
function VerifyForm() {
VerUser();
VerPasses();
VerGen();
alert(FinalMsg);
}
function VerUser(){
var vus = document.getElementById("username").value;
if(vus.length=0)
{
FinalMsg+="type username";
}
}
function VerPasses(){
var vpasfir = document.getElementById("pass1").value;
var vpassec = document.getElementById("pass2").value;
if(vpasfir.length=0)
{
FinalMsg+="type password";
}
if(vpassec.length=0)
{
FinalMsg+="type the secondary pass";
}
if (vpasfir.value != vpassec.value)
{
FinalMsg+="passs aren't match";
}
}
function VerGen() {
var vgen1 = document.getElementById("male").value;
var vgen2 = document.getElementById("female").value;
var vgen3 = document.getElementById("other").value;
if ((vgen1.checked==false)&&(vgen2.checked==false)&&(vgen3.checked==false&&)){
FinalMsg += "haven;t chosen gender";
}
}
</script>
</head>
<body dir="rtl">
<center> <img src="Title.gif" width="500px"/></center>
<form id="FormAboutYou" runat="server" method="post" onsubmit="validateForm()">
<table border="0">
<tr>
<td class="field">שם משתמש</td>
<td><input type="text" name="username" id="username"/></td>
</tr>
<tr>
<td class="field">סיסמה</td>
<td><input type="password" name="pass1" id="pass1"/></td>
</tr>
<tr>
<td class="field">סיסמה בשנית</td>
<td><input type="password" name="pass2" id="pass2"/></td>
</tr>
<tr>
<td class="field">כתובת דוא"ל</td>
<td><input type="email" name="email" id="email"/></td>
</tr>
<tr>
<td class="field">מזונות מועדפים</td>
<td Class="ChooseFrom">
<input type="checkbox" name="food" value="Choclate" id="choc" /> שוקולד <br />
<input type="checkbox" name="food" value="Fries" id="fries"/> צ'יפס <br />
<input type="checkbox" name="food" value="Tomatoes and other vegetables" id="veg"/> ירקות ופירות <br />
<input type="checkbox" name="food" value="Pasta" id="pasta"/> פסטה <br />
<input type="checkbox" name="food" value="Cheese" id="che"/>גבינה <br />
</td>
</tr>
<tr>
<td class="field">מגדר</td>
<td class="ChooseFrom">
<input type="radio" name="gender" value="Male" id="male"/> זכר <br />
<input type="radio" name="gender" value="Female" id="femle"/> נקבה <br />
<input type="radio" name="gender" value="Unde" id="other"/> עדיין לא החלטתי/יש לי בעיה עם שדות בינארים <br />
</td>
</tr>
<tr>
<td class="field">living in</td>
<td>
<select>
<option value="TelAviv" id="ny">new york</option>
<option value="PetaTikwa" id="rome">rome</option>
<option value="QiryatOno" id="Paris">Paris</option>
<option value="RamgatGan" id="lv">Las Vegas</option>
<option value="Haifa" id="ln">London</option>
<option value="Qraiot" id="bt">Bairut</option>
<option value="Bash" id="bej">Beijing</option>
<option value="Eilat" id="tk">Tokyo</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit" value="הזן נתוניך על פני המים" onsubmit="VerifyForm();"/>
</td>
</tr>
</table>
</form>
<hr />
<br /><br /><br /><br />
<br /><br /><br /><br />
</body>
</html>
thanks again :)
An idea could be to take onsubmit() out of the form tag.
then for your button change the onSubmit to onclick='return verifyForm();
In your verifyForm() method you need to return either true or false; if false, the form won't submit.
So, something like this at the end of your verifyForm()
if (FinalMsg == ""){
return true;
}else{
return false;
}

Categories