I have two forms in a single page, and both have a save button respectively.
Whenever I click the other button, I want the changes that I added on the other form to be saved as well.
This is my code:
<div id="contentMain">
#using (Html.BeginForm("ClientLocationSave", "Client", FormMethod.Post, new { id = "clientLocForm" }))
{
<input type="hidden" id="clientId" name="clientId" value="#ViewBag.ClientId" />
<input type="hidden" id="clientLocId" name="clientLocId" value="#clientLocId" />
<h2>
Client Location #pageAction</h2>
<div class="main">
<p>
<label for="txtName">
Name</label>
<span>
<input type="text" id="txtName" name="txtName" class="validate[required] inputLong" value="#clientLocName" />
</span>
</p>
<p>
<label for="txtAddress1">
Address 1</label>
<span>
<input type="text" id="txtAddress1" name="txtAddress1" class="validate[required] inputLong" value="#addressLine1" />
</span>
</p>
<p>
<label for="txtAddress2">
Address 2</label>
<span>
<input type="text" id="txtAddress2" name="txtAddress2" class="inputLong" value="#addressLine2" />
</span>
</p>
<p>
<label for="txtCity">
City</label>
<span>
<input type="text" id="txtCity" name="txtCity" class="validate[required] inputLong" value="#city" />
</span>
</p>
<p>
<label for="ddlState">
State</label>
<span>
#Html.DropDownList("ddlState", new SelectList(ViewBag.StateList, "ID", "Display_Value", state), "[Please Select]",
new Dictionary<string, object>
{
{"class","validate[required] inputLong"}
})
</span>
</p>
<p>
<label for="txtZipCode">
Zip Code</label>
<span>
<input type="text" id="txtZipCode" name="txtZipCode" class="validate[required,custom[onlyNumberSp],maxSize[20]] inputLong" value="#zipCode" />
</span>
</p>
</div>
<input type="submit" id="btnSave" class="styledButton" value="Save" />
}
<div class="main">
#using (Html.BeginForm("ClientLocationContactSave", "Client", FormMethod.Post, new { id = "contactForm" }))
{
<input type="hidden" id="clientId" name="clientId" value="#clientId" />
<input type="hidden" id="clientLoctContactId" name="clientLoctContactId" value="#clientLoctContactId" />
<input type="hidden" id="clienLocatId" name="clienLocatId" value="#clientLocId" />
<p>
<label for="ddlContact">
Contact Type</label>
<span>
#Html.DropDownList("ddlContact", new SelectList(ViewBag.ContactType, "ID", "Display_Value", contactTypeLookId), "[Please Select]",
new Dictionary<string, object>
{
{"class","validate[required] inputLong"}
})
</span>
</p>
<p>
<label for="txtValue">
Contact Value</label>
<span>
<input type="text" id="txtValue" name="txtValue" class="validate[required] inputLong"
value="" />
<p>
<label for="chkSaveIsPrimary">
Is Primary</label>
<input type="checkbox" name="chkSaveIsPrimary" id="chkSaveIsPrimary" value="true" checked="checked" />
</p>
</span>
</p>
<script type="text/javascript">
$(document).ready(function () {
var disableFields = $('#clienLocatId').val();
if (disableFields == 0) {
$('#disable').attr("hidden", false);
$('#txtValue').attr("disabled", true);
$('#ddlContact').attr("disabled", true);
$('#chkSaveIsPrimary').attr("disabled", true);
}
else {
$('#disable').attr("hidden", true);
$('#txtValue').attr("disabled", false);
$('#ddlContact').attr("disabled", false);
$('#chkSaveIsPrimary').attr("disabled", false);
}
});
</script>
<p>
<span>
<input type="submit" id="btnAddLocationContact" name="btnAddLocationContact" class="styledButton"
value="Add Contact" />
</span>
</p>
}
</div>
CONTROLLER:
public ActionResult ClientLocationSave(FormCollection formCollection)
{
String msg = String.Empty;
String newClientLocationId = String.Empty;
String clientId = formCollection["clientId"];
String clientLocId = formCollection["clientLocId"];
String locationName = formCollection["txtName"];
String address1 = formCollection["txtAddress1"];
String address2 = formCollection["txtAddress2"];
String city = formCollection["txtCity"];
String state = formCollection["ddlState"];
String zipCode = formCollection["txtZipCode"];
Client_Location clientLoc = new Client_Location();
try
{
if (String.IsNullOrWhiteSpace(clientLocId) || clientLocId == "0")
{
clientLoc.ClientID = Convert.ToInt32(clientId);
clientLoc.Name = locationName.Trim();
clientLoc.Address_Line1 = address1;
clientLoc.Address_Line2 = address2;
clientLoc.City = city;
clientLoc.State_LookID = Convert.ToInt32(state);
clientLoc.ZipCode = zipCode;
clientLoc.DateCreated = DateTime.UtcNow;
clientLoc.DateModified = DateTime.UtcNow;
clientLoc.CreatedBy = User.Identity.Name;
clientLoc.ModifiedBy = User.Identity.Name;
db.Client_Location.Add(clientLoc);
}
else
{
int id = Convert.ToInt32(clientLocId);
clientLoc = (from a in db.Client_Location
where a.ID == id
select a).SingleOrDefault();
clientLoc.Name = locationName.Trim();
clientLoc.Address_Line1 = address1;
clientLoc.Address_Line2 = address2;
clientLoc.City = city;
clientLoc.State_LookID = Convert.ToInt32(state);
clientLoc.ZipCode = zipCode;
clientLoc.DateModified = DateTime.UtcNow;
clientLoc.ModifiedBy = User.Identity.Name;
}
}
catch (Exception)
{
msg = "Failed to save";
}
db.SaveChanges();
if (String.IsNullOrWhiteSpace((msg)))
{ TempData["message"] = "Client Location Saved Successfully."; }
else if (msg != "")
{ TempData["message"] = msg; }
newClientLocationId = clientLoc.ID.ToString();
return RedirectToAction("ClientLocationDetails", new { clientId = clientId, clientLocId = newClientLocationId });
}
public ActionResult ClientLocationContactSave(FormCollection formCollection)
{
String msg = String.Empty;
String clientId = formCollection["clientId"];
String clientLoctContactId = formCollection["clientLoctContactId"];
String clienLocatId = formCollection["clienLocatId"];
bool isPrimary = Convert.ToBoolean(formCollection["chkSaveIsPrimary"]);
String value = formCollection["txtValue"];
String contactTypeLookId = formCollection["ddlContact"];
Client_Location_Contact clientLoc = new Client_Location_Contact();
try
{
if (String.IsNullOrWhiteSpace(clientLoctContactId) || clientLoctContactId == "0")
{
clientLoc.Client_LocationID = Convert.ToInt32(clienLocatId);
clientLoc.Value = value.Trim();
clientLoc.IsPrimary = isPrimary;
clientLoc.ContactType_LookID = Convert.ToInt32(contactTypeLookId);
clientLoc.DateCreated = DateTime.UtcNow;
clientLoc.DateModified = DateTime.UtcNow;
clientLoc.CreatedBy = User.Identity.Name;
clientLoc.ModifiedBy = User.Identity.Name;
db.Client_Location_Contact.Add(clientLoc);
}
else
{
int id = Convert.ToInt32(clientLoctContactId);
clientLoc = (from a in db.Client_Location_Contact
where a.ID == id
select a).SingleOrDefault();
clientLoc.Value = value.Trim();
clientLoc.IsPrimary = isPrimary;
clientLoc.ContactType_LookID = Convert.ToInt32(contactTypeLookId);
clientLoc.DateModified = DateTime.UtcNow;
clientLoc.ModifiedBy = User.Identity.Name;
}
}
catch (Exception)
{
msg = "Failed to save";
}
db.SaveChanges();
if (String.IsNullOrWhiteSpace((msg)))
{ TempData["message"] = "Contact Saved Successfully."; }
else if (msg != "")
{ TempData["message"] = msg; }
ViewBag.clientLoctContactId = clientLoctContactId;
ViewBag.clienLocatId = clienLocatId;
return RedirectToAction("ClientLocationDetails", new { clientLocId = clienLocatId, clientId = clientId });
}
Can this be done with jQuery, and if yes - how?
Lets reword your question a little into something more abstract to help you:
You have two paper forms that need to be signed and given to your manager. One has to be given to Fred in HR, another to Wilma in Sales on the other side of the building.
Can you leave your desk and get both signed at once? Of course not. You need to pick one to do first and then go to the second one before finally arriving at your manager with both forms signed.
The same is true for your page, you can bundle it all into one form and submit it to the server, handle the first part, then get some other code to handle the second part, then return the result to the user.
While there is some fancy trickery you can use to get around this, you need to ask yourself why you would want to. If you always save both forms then why bother having two?
Related
I am currently working with forms and javascript validation.. i have completed most of my code and am on the last step however cant seem to get it working and not sure what ive done wrong.. spent hours on this last part before i looked for help.
basically a user inputs their information into a form and then when they click submit the information get validated, and the inputed info moves onto a confirmation page.. at the moment the input i put in doesnt get validated anymore and is blank in the confirmation page..
First HTML register page
<form id="regform" method="post" action="confirm.html"
novalidate="novalidate">
<fieldset id="person">
<legend>Your details:</legend>
<p><label for="firstname">Enter your first name</label>
<input type="text" name="firstname" id="firstname" size="20"
/>
</p>
<p><label for="lastname">Enter your last name</label>
<input type="text" name="lastname" id="lastname" size="20" />
</p>
<fieldset id="species">
<legend>Species:</legend>
<label for="human">Human</label>
<input type="radio" name="species" id="human"
value="Human"/><br />
<label for="dwarf">Dwarf</label>
<input type="radio" name="species" id="dwarf"
value="Dwarf" /><br />
<label for="elf">Elf</label>
<input type="radio" name="species" id="elf"
value="Elf" /><br />
<label for="hobbit">Hobbit</label>
<input type="radio" name="species" id="hobbit"
value="Hobbit" /><br />
</fieldset>
<p><label for="age">Enter your age</label>
<input type="text" id="age" name="age" size="5">
</p>
</fieldset>
<fieldset id="trip">
<legend>Your trip:</legend>
<fieldset>
<legend>Booking:</legend>
<label for="1day">1 Day Tour - $200 </label>
<input type="checkbox" name="1day" id="1day"
value="1day" /><br />
<label for="4day">4 Day Tour - $1500</label>
<input type="checkbox" name="4day" id="4day"
value="4day" /><br />
<label for="10day">10 Day Tour - $3000</label>
<input type="checkbox" name="10day" id="10day"
value="10day" /><br />
</fieldset>
<p>
<label for="food">Menu preferences</label>
<select name="food" id="food">
<option value="none">Please select</option>
<option value="lembas">Lembas</option>
<option value="mushrooms">Mushrooms</option>
<option value="ent">Ent Draft</option>
<option value="cram">Cram</option>
</select>
</p>
<p>
<label for="partySize">Number of Travellers</label>
<input type="text" id="partySize" name="partySize" maxlength="3"
size="3" />
</p>
</fieldset>
<div id="bottom"> </div>
<p><input type="submit" value="Book Now!" />
<input type="reset" value="Reset" />
</p>
Validation for Javascript
function validate() {
var errMsg = "";
var result = true;
var firstname = document.getElementById("firstname").value;
var lastname = document.getElementById("lastname").value;
if (!firstname.match(/^[a-zA-Z]+$/)) {
errMsg = errMsg + "Your first name must only contain alpha characters\n";
result = false;
}
if (!lastname.match(/^[a-zA-Z+$]/)) {
errMsg = errMsg + "Your last name must only contain alpha characters\n";
result = false;
}
var age = document.getElementById("age").value;
if (isNaN(age)) {
errMsg = errMsg + "your age must be a number\n";
result = false;
}
else if (age < 18) {
errMsg = errMsg + " your age must be 18 or older\n";
result = false;
}
else if (age >= 10000) {
errMsg = errMsg + "your age must be between 18 and 10000\n";
result = false;
}
else {
var tempMsg = checkSpeciesAge(age);
if (tempMsg != "") {
errMsg + tempMsg;
result = false;
}
var partySize = document.getElementById("partySize").value;
if (isNaN(partySize)) {
errMsg = errMsg + "your age must be a number\n";
result = false;
}
else if (partySize < 1) {
errMsg = errMsg + " party size must be greater than 0\n";
result = false;
}
else if (age >= 100) {
errMsg = errMsg + "your party size must be less or equal to 100\n";
result = false;
}
}
var is1day = document.getElementById("1day").checked;
var is4day = document.getElementById("4day").checked;
var is10day = document.getElementById("10day").checked;
if (!(is1day || is4day || is10day)) {
errMsg = errMsg + "please select at least one trip.\n";
result = false;
}
if (document.getElementById("food").value == "none") {
errMsg = errMsg + "You must select a food preference. \n ";
result = false;
}
var human = document.getElementById("human").checked;
var dwarf = document.getElementById("dwarf").checked;
var elf = document.getElementById("elf").checked;
var hobbit = document.getElementById("hobbit").checked;
if (!(human || dwarf || elf || hobbit)) {
errMsg = errMsg + "please select a spiecies";
result = false;
}
if (errMsg !== "") {
alert(errMsg);
}
if (result) {
storeBooking(firstname, lastname, age, species, is1day, is4day, is10day);
}
return result;
}
function getSpecies() {
var speciesName = "Unknown";
var speciesArray = document.getElementById("species").getElementsByTagName("input");
for (var i = 0; i < speciesArray.length; i++){
if (speciesArray[i].checked)
speciesName = speciesArray[i].value;
}
return speciesName;
}
function checkSpeciesAge(age) {
var errMsg = "";
var species = getSpecies();
switch(species){
case "human":
if (age > 120) {
errMsg = "you cannot be a Human and over 120. \n";
}
break;
case "dwarf":
case "hobit":
if (age > 150 ){
errMsg = " YOu can not be a " + species + " and over 150 .\n ";
}
break;
case "elf":
break;
default:
errMsg = " we dont allow your kind on our tours. \n";
}
return errMsg;
}
function storeBooking(firstname, lastname, age, species, is1day, is4day, is10day){
var trip= "";
if(is1day) trip ="1day";
if(is4day) trip +=", 4day";
is(is10day) trip += ", 10day";
sessionStorage.trip = trip;
sessionStorage.firstname= firstname;
sessionStorage.lastname= lastname;
sessionStorage.age = age;
sessionStorage.species= species;
sessionStorage.partySize= partySize;
sessionStorage.food = food;
alert ("Trip stored: " + sessionStorage.trip);
}
function init() {
var regForm = document.getElementById("regform");
regForm.onsubmit = validate;
}
window.onload = init;
Confirm HTML
<form id="bookform">
<fieldset>
<legend>Your Booking</legend>
<p>Your Name: <span id="confirm_name"></span></p>
<p>Species: <span id="confirm_species"></span></p>
<p>Age: <span id="confirm_age"></span></p>
<p>Trips booked: <span id="confirm_trip"></span></p>
<p>Food Preference: <span id="confirm_food"></span></p>
<p>Number of beings: <span id="confirm_partySize"></span></p>
<p>Total Cost: $<span id="confirm_cost"></span></p>
<input type="hidden" name="firstname" id="firstname" />
<input type="hidden" name="lastname" id="lastname" />
<input type="hidden" name="age" id="age" />
<input type="hidden" name="species" id="species" />
<input type="hidden" name="trip" id="trip" />
<input type="hidden" name="food" id="food" />
<input type="hidden" name="partySize" id="PartySize" />
<input type="hidden" name="cost" id="cost" />
<p><label for="date">Preferred Date</label>
<input type="text" id="date" name="bookday" required="required" placeholder="dd/mm/yyyy" pattern="\d{1,2}/\d{1,2}/\d{4}" title="Format dd/mm/yyyy" maxlength="10" size="10" />
</p>
<input type="submit" value="Confirm Booking" />
<button type="button" id="cancelButton">Cancel</button>
</fieldset>
Javascrips file 2 to bring the info over to the confirmation
function validate(){
var errMsg = "";
var result = true;
return result;
function calcCost(trips, partySize){
var cost = 0;
if (trips.search("1day") != -1) cost = 200;
if (trips.search("4day")!= -1) cost += 1500;
if (trips.search("10day")!= -1) cost += 3000;
return cost * partySize;
}
function getBooking(){
var cost = 0;
if(sessionStorage.firstname != undefined){
//confirmation text
document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;
document.getElementById("confirm_age").textContent =sessionStorage.age;
document.getElementById("confirm_trip").textContent = sessionStorage.trip;
document.getElementById("confirm_species").textContent = sessionStorage.species;
document.getElementById("confirm_food").textContent =sessionStorage.food;
document.getElementById("confirm_partySize").textContent = sessionStorage.partySize;
cost = calcCost(sessionStorage.trip, sessionStorage.partySize);
document.getElementById("confirm_cost").textContent = cost;
//fill hidden fields
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("age").value = sessionStorage.age;
document.getElementById("species").value = sessionStorage.species;
document.getElementById("food").value = sessionStorage.food;
document.getElementById("partySize").value = sessionStorage.partySize;
document.getElementById("cost").value = cost;
}
}
function init () {
var bookForm = document.getElementById("bookform");
bookForm.onsubmit = validate;
}
window.onload = init;
There are a couple of syntax errors that should be clearly visible when you open your browser console:
- errMsg + tempMsg; is not a complete statement,
- is(is10day) trip += ", 10day"; is not valid, and
- storeBooking doesn't have a parameter called partySize
I see a couple of logic errors too:
- checkSpeciesAge will never return an empty string as validate expects, and
- the section of code that attempts to validate partySize has several errors (including that this entire structure is nested inside the age-validation section's else block.)
A few console.log statements could go a long way toward identifying where your variables contain values that you don't expect if there are still bugs to track down after correcting these issues. Good luck!
I tried to fix this, and make some changes in your code. according to your requirement
follow the link of jsfiddle; https://jsfiddle.net/dupinderdhiman/vno15jku/32/
<form id="bookform">
<fieldset>
<legend>Your Booking</legend>
<p>Your Name: <span id="confirm_name"></span></p>
<p>Species: <span id="confirm_species"></span></p>
<p>Age: <span id="confirm_age"></span></p>
<p>Trips booked: <span id="confirm_trip"></span></p>
<p>Food Preference: <span id="confirm_food"></span></p>
<p>Number of beings: <span id="confirm_partySize"></span></p>
<p>Total Cost: $<span id="confirm_cost"></span></p>
<input type="hidden" name="firstname" id="firstname" />
<input type="hidden" name="lastname" id="lastname" />
<input type="hidden" name="age" id="age" />
<input type="hidden" name="species" id="species" />
<input type="hidden" name="trip" id="trip" />
<input type="hidden" name="food" id="food" />
<input type="hidden" name="partySize" id="PartySize" />
<input type="hidden" name="cost" id="cost" />
<p><label for="date">Preferred Date</label>
<input type="text" id="date" name="bookday" required="required" placeholder="dd/mm/yyyy" pattern="\d{1,2}/\d{1,2}/\d{4}" title="Format dd/mm/yyyy" maxlength="10" size="10" />
</p>
<input type="submit" value="Confirm Booking"/>
<button type="button" id="cancelButton">Cancel</button>
</fieldset>
<script>
sessionStorage.trip = "4day";
sessionStorage.firstname= "firstname";
sessionStorage.lastname= "lastname";
sessionStorage.age = 21;
sessionStorage.species= "species";
sessionStorage.partySize= 10;
sessionStorage.food = "food";
function validate(){
var errMsg = "";
var result = true;
return result;
}
function calcCost(trips, partySize){
var cost = 0;
if (trips.search("1day") != -1) cost = 200;
if (trips.search("4day")!= -1) cost += 1500;
if (trips.search("10day")!= -1) cost += 3000;
return cost * partySize;
}
function loadDataFromSession(){
var cost = 0;
if(sessionStorage.firstname != undefined){
//confirmation text
document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;
document.getElementById("confirm_age").textContent =sessionStorage.age;
document.getElementById("confirm_trip").textContent = sessionStorage.trip;
document.getElementById("confirm_species").textContent = sessionStorage.species;
document.getElementById("confirm_food").textContent =sessionStorage.food;
document.getElementById("confirm_partySize").textContent = sessionStorage.partySize;
cost = calcCost(sessionStorage.trip, sessionStorage.partySize);
document.getElementById("confirm_cost").textContent = cost;
//fill hidden fields
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("age").value = sessionStorage.age;
document.getElementById("species").value = sessionStorage.species;
document.getElementById("food").value = sessionStorage.food;
document.getElementById("partySize").value = sessionStorage.partySize;
document.getElementById("cost").value = cost;
}
}
function init () {
loadDataFromSession();
var bookForm = document.getElementById("bookform");
bookForm.onsubmit = validate;
}
window.onload = init;
</script>
so what is the major change:
Created one function loadDataFromSession which call on init();
remove code from getBooking() add to loadDataFromSession.
now click on submit and your form will be submit
var labelsarray = document.getElementsByTagName("label");
var inputsarray = document.getElementsByTagName("input");
var array = [];
function agecal() {
var Bdate = inputsarray[4].value;
var Bday = +new Date(Bdate).getFullYear();
var age = (new Date().getFullYear() - Bday);
inputsarray[5].value = age;
}
function subm() {
var users = {
FirstName: inputsarray[0].value,
LastName: inputsarray[1].value,
UserName: inputsarray[2].value,
Password: inputsarray[3].value,
DateofBirth: inputsarray[4].value,
Age: inputsarray[5].value,
Purpose: ""
};
if (inputsarray[6].checked === true) {
users.Gender = "Male";
} else if (inputsarray[7].checked === true) {
users.Gender = "Female";
}
if (inputsarray[8].checked === true) users.Purpose += " Storing Apps";
if (inputsarray[9].checked === true) users.Purpose += " Storing Sites";
if (inputsarray[10].checked === true) users.Purpose += " Fun";
array.push(users);
localStorage.setItem("Users Data: ", JSON.stringify(array));
var item = localStorage.getItem("Users Data: ");
var arrayobjfromls = JSON.parse(item);
for (var i = 0; i < arrayobjfromls.length; i++) {
if (inputsarray[2].value === arrayobjfromls[i].UserName) {
alert("This username is already in use. Please try another.");
localStorage.removeItem(arrayobjfromls[i]);
}
}
}
<div>
<center>
<form action="javascript:void(0);" method="post" onsubmit="subm();">
<label for="fname">First Name:</label>
<input type="text" id="fname" />
<br/>
<label for="lname">Last Name:</label>
<input type="text" id="lname" />
<br/>
<label for="uname">User Name:</label>
<input type="text" id="uname" />
<br/>
<label for="pass">Password:</label>
<input type="password" id="pass" />
<br/>
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" onchange="agecal();" />
<br/>
<label>Age:</label>
<input type="text" id="age" disabled="disabled" />
<br/>
<span>Gender:</span>
<input type="radio" name="gender" id="male" />
<label for="male">Male</label>
<input type="radio" name="gender" id="female" />
<label for="female">Female</label>
<br/>
<p>For what purpose(s) you are making account?</p>
<input type="checkbox" id="app" name="purpose" value="storingapps" />
<label for="app">Storing Apps</label>
<input type="checkbox" id="site" name="purpose" value="storingsites" />
<label for="site">Storing Sites</label>
<input type="checkbox" id="fun" name="purpose" value="fun" />
<label for="fun">Fun</label>
<br/>
<input type="submit" value="Submit" class="button" />
</form>
</center>
</div>
Please help me I want to stop user for using username which already present in my local storage by showing an alert and also I don't want to send data to local storage in which username is same of that data which is already present in my local storage...so that my local storage contain only those objects which have different usernames.
You're already checking for this; you're just doing it after you've already added the new user. Do the check first:
var item = localStorage.getItem("Users Data: ");
var arrayobjfromls = JSON.parse(item);
var found = false;
for (var i = 0; i < arrayobjfromls.length; i++) {
if(users.UserName === arrayobjfromls[i].UserName) {
found = true;
break;
}
}
if ( found ) {
alert("This username is already in use. Please try another.");
} else {
array.push( users );
localStorage.setItem("Users Data: ", JSON.stringify(array));
}
Html - Delivery address has to give the entered value to billing address. The javascript and html are in separate files
Other js features are working fine, but its just this one that doesn't seem to work
<div class="textinput">
<label for="deladdress">Delivery Address: </label>
<input id="deladdress" type="text" name="Delivery Address" />
</div>
<div id="buttoncheckarea">
<input id="CheckDelivery" type="checkbox" name="CheckDelivery">
<label id="diff" for="CheckDelivery">Same as delivery address?</label>
</div>
<div class="textinput">
<label for="postcode">Postcode: </label>
<input id="postcode" type="text" name="postcode" />
</div>
<div class="textinput">
<label for="billaddress">Billing Address: </label>
<input id="billaddress" type="text" name="Billing Address" />
</div>
javascript
function deliveryfunc() {
var delivery = document.getElementById("deladdress").value;
var billing = document.getElementById("billaddress").value;
//var checkbox = document.getElementById("CheckDelivery").checked;
if (document.getElementsByName("CheckDelivery").checked == true) {
billing = delivery;
}
}
function init () {
var order = document.getElementById("ordForm");
order.onsubmit = ordervalidation;
order.onclick = radiobuttoncheck;
var checkbutton = document.getElementsByName("CheckDelivery");
checkbutton.onclick = deliveryfunc;
}
window.onload = init;
Try updating your deliveryfunc as below:
function deliveryfunc() {
var delivery = document.getElementById("deladdress");
var billing = document.getElementById("billaddress");
if (document.getElementById("CheckDelivery").checked == true) {
billing.value = delivery.value;
}
}
function init () {
var order = document.getElementById("ordForm");
order.onsubmit = ordervalidation;
order.onclick = radiobuttoncheck;
var checkbutton = document.getElementById("CheckDelivery");
checkbutton.onclick = deliveryfunc;
}
window.onload = init;
I made a formular and a multiple functions that check the different intputs. Those functions work.
Then I wrote a function CHECKFORMULAIRE() that use all those function to check when we submit the formular and that is supposed to return false or true. When I submit the formular with errors, I get to the next page, which is not supposed to happen..
function verifFormulaire(form){
var nomOk = verifPseudo(form.nom);
var prenomOk = verifPseudo(form.prenom);
var emailOk = verifEmail(form.email);
var telfixOk = verifTel(form.telfixe);
var telportOk = verifTel(form.telport);
var dateOk = verifDateDeNaissance(form.date);
if (nomOk && prenomOk && emailOk && telfixOk && telportOk && dateOk){
return true ;
}
else {
alert("Formulaire mal remplie");
return false;
}
}
That's why I tested this function VERIFFORMULAIRE() right in the .js to see what happens.
var form = document.getElementById('myForm');
alert(verifFormulaire(form));
The problem is that I have errors concerning the other smaller functions that I did not have before) when I call VERIFFORMULAIRE().
TypeError: champ.style is undefined
When I remove that line that is a problem, I get other errors of the same kind :
TypeError: date is undefined
Do you have an idea on how to fix this??
Thank you,
Here is the form :
<html>
<head>
<title> Formulaire page 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href ="cssformulaire.css">
</head>
<body>
<form id="myForm" method = post action = formulaire2.php onsubmit =" return verifFormulaire(this)">
<span class="form_col"> </span>
<label for="Civilité">Civilité </label> </br>
<INPUT id ="Civilité" type="checkbox" name="Civilité" value="Monsieur"> Monsieur
<INPUT id ="Civilité" type="checkbox" name="Civilité" value="Madame"> Madame
<span class = "tooltip"> Vous devez sélectionner votre sexe</span>
</br></br>
<label for="email">Votre adresse email </label> </br>
<INPUT id ="email" type="text" value="<?php $_SESSION['email'] ?>" name = "email" >
<span class = "tooltip"> Vous devez sélectionner votre adresse e-mail</span>
</br></br>
<label for="datenaissance"> Votre date de naissance </label> </br>
<input id="datenaissance" type = "date" name = "datenaissance" onblur = "verifDateDeNaissance(this)">
<span class = "tooltip"> JJ/MM/AAAA</span>
</br></br>
<label class = "form_col" for = "nom"> Nom : </label>
<input id = "nom" type = "text" name = "nom" onclick ="colorselected(this)" onblur="verifPseudo(this);blurselected(this)" >
<span class = "tooltip"> Plus de 2 caractères</span>
</br></br>
<label for="prénom"> Prénom </label> </br>
<input id="prénom" type = "text" name = "prenom" onclick ="colorselected(this)" onblur="verifPseudo(this);blurselected(this)">
<span class = "tooltip"> Plus de 2 caractères</span>
</br></br>
<label for="telfix"> Télephone fixe </label> </br>
<input id = "telfix" type = "tel" name = "telfixe" onclick = "colorselected(this)" onblur = "verifTel(this)">
<span class = "tooltip"> Format 0XXXXXXXXX</span>
</br></br>
<label for="telport"> Télephone portable </label> </br>
<input id ="telport" type = "tel" name = "telport" onclick = "colorselected(this)" onblur = "verifTel(this)">
<span class = "tooltip"> Format 0XXXXXXXXX</span>
</br></br>
<input type="submit" value="Suivant" ></code>
<INPUT TYPE="reset" NAME="nom" VALUE="Effacer">
</form>
<script type="text/javascript" src = "javascriptform.js">
</script>
</body>
<footer>
</footer>
</html>
And here are the checking functions :
function surligne(champ, stat){
if (stat){
champ.style.backgroundColor = "#fba";
}
else
champ.style.backgroundColor = "#A9F5A9";
}
function verifPseudo(pseudo){
if (pseudo.value.length < 3){
surligne(pseudo, true);
return false;
}
else {
surligne(pseudo, false);
return true;
}
}
function verifTel(tel){
var regex = /[0-9]{10}/
if(!regex.test(tel.value)){
surligne(tel, true);
return false;
}
else {
surligne(tel, false);
return true ;
}
}
function verifDateDeNaissance(date){
var regex = /[0-9]{2}\/[0-9]{2}\/[1-2][0-9][0-9][0-9]/
if(!regex.test(date.value)){
surligne(date, true);
return false;
}
else {
surligne(date, false);
return true ;
}
}
function verifEmail(email){
var regex = /[a-zA-Z0-9._-]+#[a-z0-9._-]{2,}\.[a-z]{2,4}/;
if (!regex.test(email.value)){
surligne(email,true);
return false;
}
else {
surligne(email, false);
return true;
}
}
function colorselected(champ){
champ.style.borderColor = "#81BEF7";
}
function blurselected(champ){
champ.style.borderColor="";}
I think that the issue is that form.date does not exist
You can change
<input id="datenaissance" type = "date" name = "datenaissance" onblur = "verifDateDeNaissance(this)">
To
<input id="datenaissance" type = "date" name = "date" onblur = "verifDateDeNaissance(this)">
So I have this code, which I am trying to use to make it update my form text boxes when I select a different drop down user.
Here's the code:
<script type="text/javascript">
document.getElementById("useruname").onchange = function() {
var selecteduname = this.value;
}
var xmlhttp;
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
function updateAdduser()
{loadXMLDoc();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var json = xmlhttp.responseText;
var fields = JSON.parse(json);
Object.keys(fields).forEach(function (name) {
var input = document.getElementsByName(name);
input.value = fields[name];
});
}
}
xmlhttp.open("GET", "ajaxuseradd.psp?=", true);
xmlhttp.send();
}
</script>
<form action="adduser.psp" method="get">
<fieldset>
<label for="uname">Username:</label>
<select name="uname" id="useruname" onChange="updateAdduser();">
<%
import MySQLdb
db = MySQLdb.connect("localhost", "login", "password", "somethingelse")
c = db.cursor()
c.execute("""SELECT user from employees;""")
tup = c.fetchall()
tupstr = str(tup)
tupstr = tupstr.replace("(", "").replace("'", "").replace(")", "").replace(",,", ",").replace("'", "").replace("' ", "'").replace(", ", ",")
tupstr = tupstr.rstrip(",")
numlist = tupstr.split(",")
optionlist = ['<option value="%s">%s</option>' % (x, x) for x in numlist]
options = "\n".join(optionlist)
%>
<%= options %>
</select>
</fieldset>
<fieldset>
<label for="fname">First Name:</label>
<input type="text" name="fname" />
</fieldset>
<fieldset>
<label for="lname">Last Name:</label>
<input type="text" name="lname" />
</fieldset>
<fieldset>
<label for="email">Email:</label>
<input type="text" name="email">
</fieldset>
I would seriously consider moving to using a client javascript library like jQuery.
Your code would be simplified to something like this:
<script type="text/javascript">
$("#useruname").change = function() {
var selecteduname = this.value;
}
function updateAdduser()
{
var fields = null;
$.ajax(url: "ajaxuseradd.psp?=",
dataType = 'json',
success: function(data){
fields = data;
Object.keys(fields).forEach(function (name) {
var input = $(name);
input.value = fields[name];
});
}
});
}
</script>
<form action="adduser.psp" method="get">
<fieldset>
<label for="uname">Username:</label>
<select name="uname" id="useruname" onChange="updateAdduser();">
<%
import MySQLdb
db =
c = db.cursor()
c.execute("""SELECT user from employees;""")
tup = c.fetchall()
tupstr = str(tup)
tupstr = tupstr.replace("(", "").replace("'", "").replace(")", "").replace(",,", ",").replace("'", "").replace("' ", "'").replace(", ", ",")
tupstr = tupstr.rstrip(",")
numlist = tupstr.split(",")
optionlist = ['<option value="%s">%s</option>' % (x, x) for x in numlist]
options = "\n".join(optionlist)
%>
<%= options %>
</select>
</fieldset>
<fieldset>
<label for="fname">First Name:</label>
<input type="text" name="fname" />
</fieldset>
<fieldset>
<label for="lname">Last Name:</label>
<input type="text" name="lname" />
</fieldset>
<fieldset>
<label for="email">Email:</label>
<input type="text" name="email">
</fieldset>