js or CSS is not working - javascript

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

Related

Javascript function to check if a date entered in the "datetime" form field is not a past date and only today's or some future date

I want to use date-time field in HTML as below. However I want to use that value to check that the date is either today's or a future date and not a past date.
I checked other questions on somewhat similar topic but they didn't really help in any way. Is there any way one can extract date from date-time field because when we use the value of the field, we get numbers and alphabets which do not make any sense to me.
<html>
<script type="text/javascript">
function checknum()
{
var num_ch=document.forms["bookticketpage"]["childrens"].value;
var num_tk=document.forms["bookticketpage"]["tickets"].value;
if(num_ch > num_tk)
{
alert("No of tickets should be greater than the no of children");
}
}
function calcfare()
{
var tick = document.forms["bookticketpage"]["tickets"].value;
var ch=document.forms["bookticketpage"]["childrens"].value;
var total = (tick-ch)*200 + ch*100;
alert("Your approximate ticket amount is " + total + " INR");
}
</script>
<body>
<style type="text/css" >
.item img {
height: 200px;
width: 200px;
-webkit-transition: all 2s ease;
-moz-transition: all 2s ease;
-ms-transition: all 2s ease;
transition: all 2s ease; }
.item img:hover
{
width: 300px;
height: 300px;
}
</style>
<form name="bookticketpage" action="thankyou.html" method="post">
<div>
<h2><b>Movie Ticket Booking</b></h2>
<table>
<!------------------------------------------------------------------>
<tr>
<td>
<label for="username">Name</label>
</td>
<td>
<input type="text" name="username" placeholder="Enter the name" size="20"
required pattern="[a-zA-Z\s]+">
</td>
</tr>
<!------------------------------------------------------------------>
<tr>
<td>
<label for="moviename">Movie Name</label>
</td>
<td>
<datalist id="movies">
<option value="Irada"></option>
<option value="Rangoon"></option>
<option value="Logan"></option>
<option value="Fist Fight"></option>
</datalist>
<input list="movies" name="moviename" size="20" required="true"/>
</td>
</tr>
<!------------------------------------------------------------------>
<tr>
<td>
<label for="circle">Circle</label>
</td>
<td>
<datalist id="circles">
<option value="Silver"></option>
<option value="Gold"></option>
<option value="Platinum"></option>
</datalist>
<input list="circles" name="circle" size="20" required="true"/>
</td>
</tr>
<tr>
<td>
<label for="phone">Phone no</label>
</td>
<td>
<input type="tel" name="phone" placeholder="Enter Mobile # here" required
pattern="[1-9]{1}[0-9]{9}" >
</td>
</tr>
<tr>
<td>
<label for="showdate">Show date and time</label>
</td>
<td>
<input type = "datetime-local" name="showdate required="true"">
</td>
</tr>
<tr>
<td>
<label for="tickets">No of tickets</label>
</td>
<td>
<input type="text" name="tickets" size="20" min="1" max="10"
required="true">
</td>
</tr>
<tr>
<td>
<label for="childrens">No of childrens</label>
</td>
<td>
<input type="text" name="childrens" size="20" min="1" max="5"
required="true">
</td>
</tr>
<!------------------------------------------------------------------->
<tr>
<td>
<label for="Book My Show"><input type = "submit" value ="Book My Show"
onClick="checknum(); calcfare();"/></label>
</td>
<td>
<label for="reset"><input type="reset" value="Reset"/></label>
</td>
</tr>
</table>
<div class="item">
<img src="contactus.jpg" width="254" height="54">
<div class="item-overlay top"></div>
</div>
</div>
</form>
</body>
</html>
Try this:
function myFunction(){
var inputDate = new Date(document.getElementById("bookingday").value);
var date = new Date();
if(inputDate < date){
alert("Please enter valid date");
}else{
alert("Valid date. Thank you");
}
}
Enter a booking date:<br>
<input type="datetime-local" id="bookingday"><br>
<button onclick="myFunction()">Click me</button>
function setMinDate() {
var dateInput = document.getElementById('date');
var str = new Date().toISOString();
console.log(str);
str = str.substring(0, str.length - 1);
dateInput.setAttribute('min', str);
console.log(dateInput);
}
setMinDate();
<form>
    <label for="party">DATE:</label>
    <input id="date" type="datetime-local" name="partydate" >
  </form>
You can set the min attribute to your input tag
<input type="datetime-local" id="date" name="showdate" required=" true " />

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
}

Need to use one field many times in one html form

I have two problems:
1- I need to enter more than one question in ContentQue field. First click on "Add New Question" button then enter a question, click OK, show the data, then again click on "Add New Question" button, but in this time the input is not shown?
2- I want to force the user to choose one module from select.
Thanks in advanced
<head>
<meta charset="utf-8">
<title>Add New Item</title>
<style>
#myquelist
{
overflow-y:scroll;
}
// To force the user enter data
.btn
{
background-color:#336;
color:#CC6;
border-radius:10px;
padding:10px 10px 10px 10px;
margin:10px 10px 10px 10px;
opacity:0.5;
}
.txt
{
background-color:#09F;
color:#009;
border-radius:10px;
}
.err
{
color:#F00;
}
</style>
<!-- Java Script-->
<script src="jquery-1.11.3.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#btnquestion').click(function () {
$('#myquelist').hide('fast');
$('#Type3').show('fast');
});
$('#btnOK').click(function () {
var a=$('#ContentQue').val();
var b=$('#qlist').val();
var c=b+"<br>"+a;
$('#qlist').val(c);
$('#ContentQue').val('');
document.getElementById("Type3").style.height="150px";
document.getElementById("Type3").innerHTML=c;
$('#myquelist').show('fast');
});
$('#myquelist').hide('fast');
$('#Type3').hide('fast');
$('#Type2').hide('fast');
$('#ExamType1').click(function () {
$('#Type2').hide('fast');
$('#Type3').hide('fast');
$('#Type1').show('fast');
});
$('#ExamType2').click(function () {
$('#Type1').hide('fast');
$('#Type3').hide('fast');
$('#Type2').show('fast');
});
$('#ExamType3').click(function () {
$('#Type1').hide('fast');
$('#Type2').hide('fast');
alert("A");
//$('#myquelist').show('fast');
$('#Type3').show('fast');
});
// To force the user enter data in text box
$(" :text" ).addClass("txt");
$("p").hide();
$("#PageBody input:text select").blur(function()
{
if(!$(this).val())
{
$(this).parent("div").children("p").show();
$(this).parent("div").children("p").addClass("err");
}
else
{
$(this).parent("div").children("p").hide();
}
});
});
</script>
</head>
<body id="PageBody">
<header><h2>New Exam</h2></header>
<form id="form1">
<table width="100%" border="2" cellspacing="5px" cellpadding="5px">
<tr>
<th><b>Assignment Title :
<td><div><input type="text" name="ExamTitle" autofocus ><p>Please Exam Title</p></div></td>
</tr>
<tr>
<th><b>Exam Type</b></th>
<td>
<input type="radio" name="ExamType" value="File" id="ExamType1" checked="checked">File
<input type="radio" name="ExamType" value="Text" id="ExamType2">Text
<input type="radio" name="ExamType" value="Questions" id="ExamType3">Questions
<div id="Type1">
<input type="file" name="fileToUpload" id="fileToUpload">
</div>
<div id="Type2">
<input type="text" name="ContentText" class="hidden" autofocus>
</div>
<div id="myquelist">
<button id="btnquestion" type="button" name="AddNew" class="hidden">Add New Question</button>
</div>
<div id="Type3">
<input type="text" id="ContentQue" name="ContentQue" >
<button type="button" id="btnOK" name="OK" >OK</button>
</div>
<input type="hidden" id="qlist" name="qlist">
</td>
</tr>
<tr>
<th><b>Module :</b></th>
<td>
<select id="Modl" name="Modl" >
<option selected="selected" disabled="disabled" >Choose Module</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
</td>
</tr>
<!-- Other inputs -->
<tr>
<td align="center" colspan="2">
<input type="submit" name="SaveBtn" style="width:95px;height:50px"; value="Save" />
</td>
</tr>
</table>
</form>
<?php
$qlist = $_POST["qlist"];
?>
</body>
</html>
This needed a fair amount of work. I had to clean up a few HTML issues and change the logic some.
First, much easier to use an Array to store the various questions. I would pass the array to your form handler, but I populated the qlist as you were shooting for.
Second, to show the questions, I used a List. Easier to work with later.
Third, I wrapped the different parts so they are easier to hide/show.
Fourth, I added in verification that a user entered a question when clicking ok and when they submit the form, to ensure they selected a Module.
HTML
<header>
<h2>New Exam</h2>
</header>
<form id="form1">
<table width="100%" border="2" cellspacing="5px" cellpadding="5px">
<tr>
<th width="135px"><b>Assignment Title : </b></th>
<td>
<div>
<input type="text" name="ExamTitle" autofocus />
<p>Please Exam Title</p>
</div>
</td>
</tr>
<tr>
<th height="80px"><b>Exam Type :</b></th>
<td valign="top">
<input type="radio" name="ExamType" value="File" id="ExamType1" checked="checked" />File
<input type="radio" name="ExamType" value="Text" id="ExamType2" />Text
<input type="radio" name="ExamType" value="Questions" id="ExamType3" />Questions
<div id="Type1">
<input type="file" name="fileToUpload" id="fileToUpload">
</div>
<div id="Type2">
<input type="text" name="ContentText" class="hidden" autofocus>
</div>
<div id="Type3">
<div id="addNew">
<button id="btnquestion" type="button" name="AddNew" class="hidden">Add New Question</button>
</div>
<div id="addQuestion" style="display: none;">
<input type="text" id="ContentQue" name="ContentQue">
<button type="button" id="btnOK" name="OK">OK</button>
</div>
<div id="showQuestions" style="display: none;">
</div>
<input type="hidden" id="qlist" name="qlist">
</div>
</td>
</tr>
<tr>
<th><b>Module :</b></th>
<td>
<select id="Modl" name="Modl">
<option selected="selected" disabled="disabled">Choose Module</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
</td>
</tr>
<!-- Other inputs -->
<tr>
<td align="center" colspan="2">
<input type="submit" name="SaveBtn" style="width:95px;height:50px;" value="Save" />
</td>
</tr>
</table>
</form>
CSS
.btn {
background-color: #336;
color: #CC6;
border-radius: 10px;
padding: 10px 10px 10px 10px;
margin: 10px 10px 10px 10px;
opacity: 0.5;
}
.txt {
background-color: #09F;
color: #009;
border-radius: 10px;
}
.err {
color: #F00;
}
#Type3 ul {
list-style: none;
margin: 0;
padding: 0;
max-height: 150px;
overflow: auto;
}
#Type3 ul li {
list-style: none;
}
JQUERY
// Set Globals
var ql = [];
$(document).ready(function() {
// Set View State
$("#Type1").show();
$("#Type2").hide();
$("#Type3").hide();
// Set Action Functions
$('#btnquestion').click(function() {
$('#addNew').hide();
$('#addQuestion').show();
$("#ContentQue").focus();
});
$('#btnOK').click(function() {
var q;
q = $('#ContentQue').val();
if (q == "") {
alert("Please enter a Question.");
$("#ContentQue").focus();
return false;
}
ql.push(q);
$('#qlist').val(ql.join(","));
$('#ContentQue').val('');
if (ql.length > 0) {
var qtext = $("<ul>");
$.each(ql, function(i, v) {
qtext.append("<li id='que-" + i + "'>" + v + "</li>");
});
$("#showQuestions").html(qtext);
}
$("#addQuestion").hide();
$('#showQuestions').show();
$("#addNew").show();
});
$("#form1 input[name='ExamType']").click(function() {
var pick = $(this).val();
switch (pick) {
case "File":
$("#Type1").show();
$("#Type2").hide();
$("#Type3").hide();
break;
case "Text":
$("#Type1").hide();
$("#Type2").show();
$("#Type3").hide();
break;
case "Questions":
$("#Type1").hide();
$("#Type2").hide();
$("#Type3").show();
break;
}
});
});
$("#form1").submit(function(e){
e.preventDefault();
if($("#Modl option").eq(0).is(":selected")){
alert("Please select a Module.");
return false;
}
return true;
});
Working Example: http://jsfiddle.net/Twisty/ax2zds1o/6/
Things you may want to consider:
A button to remove a question from the list
How many questions do you want to allow? 100? 200? 1000? How will you pass a large number of questions?
Allowing the user to arrange the order of the questions in the list before submitting

Writing and Retrieving Cookies in JS

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>

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>

Categories