I am trying to make a simple string manipulation program, but I am running into problems.
WHAT THE PROGRAM SHOULD DO:
enteredname field must have at least one space but not in the first position.
enteredname field must contain 'miller' in anycase somewhere.
State field must be only two characters long.
Zip field must start with '45'
Lastly, streetaddress field is not required to contain the word street, but if it does, it is to be changed to 'Street'.
NOT WORKING:
Currently, everything works except the 'street' name check.
ERROR LOCATION:
if (streetaddress.toLowerCase().indexOf("street") == -1)
Current code:
//need to initialize to empty strings
var enteredname = "";
var streetaddress = "";
var city = "";
var state = "";
var zip = "";
function ValidateandDisplay() {
enteredname = document.getElementById("NameTextBox").value;
streetaddress = document.getElementById("StreetAddressTextBox").value;
city = document.getElementById("CityTextBox").value;
state = document.getElementById("StateTextBox").value;
zip = document.getElementById("ZipTextBox").value;
var isValid = CheckEntries(); // call isValid function here that will
// perform all validation and return with a true or false from CheckEntries
if (isValid) {
//string to display
var correctentries = enteredname + "<br/>" +
streetaddress + "<br/>" + city + ", " + state + " " + zip;
document.getElementById("AddressDiv").innerHTML = correctentries;
}
}
function CheckEntries() {
//perform all checks here
//use separate ifs to determine each validation requirement
// alerting the user to the particular problem if something didn't
// pass validation and returning with a false
// ALL of your validation MUST be above the return true statement below
// it will only get to THIS return if all validation (conditions) were ok
if (enteredname[0] == ' ')
{
alert("First position in name field can not be a space.")
return false;
}
if (enteredname.indexOf(" ") == -1)
{
alert("no spaces found in entry.")
return false;
}
if (enteredname.toLowerCase().indexOf("miller") == -1)
{
alert("miller is not in name field.")
return false;
}
if (state.length != 2)
{
alert("State field must be only two characters long.")
return false;
}
if (zip[0] != '4' || zip[1] != '5')
{
alert("Zip field must start with 45.")
return false;
}
if (streetaddress.toLowerCase().indexOf("street") == -1)
{
streetaddress.replace("street", "Street");
return true;
}
else
return true;
}
Name: <input id="NameTextBox" type="text" /> FirstName LastName with a space between<br /> Street Address: <input id="StreetAddressTextBox" type="text" /> <br /> City: <input id="CityTextBox" type="text" /> <br /> State: <input id="StateTextBox" type="text"
/> <br /> Zip: <input id="ZipTextBox" type="text" /> <br />
<input id="Button1" type="button" value="Validate Entries" onclick="ValidateandDisplay()" />
<div id="AddressDiv">If entered correctly, your address will display here.</div>
<input id="Button1" type="button" value="Split a String" onclick="SplitThis()" />
String (array) indices start at 0
state.length > 2 ==> shoulf be "not equal"
(zip[-1] != '4' && zip[0] != '5') => It must be OR. And the indices are wrong
You are missing quotes in last if statement
Related
Trying to stop the same value(s) being submitted twice. I have created an function which allows a user to enter a name and a mark to be submitted to a simple site i am trying to create. If the same value(s) (name & mark) are entered I am trying to figure out a way to alert the user and stop the name and mark being submitted to the console.
function add() {
name.push(nameInput.value);
mark.push(markInput.value);
if (name == "" && mark == "") {
document.getElementById("result").innerHTML = "No name or mark Has Been Entered. Please Try Again!";
} else if (name && mark) {
document.getElementById("result").innerHTML = "Name & Mark has successfully been entered!";
console.log(name, mark);
} else if (name == mark) {
var n = name.includes("Ross", 0);
//console.log(name, mark);//
}
}
document.getElementById("Add").addEventListener("click", insert);
You should move name.push(nameInput.value); mark.push(markInput.value); into block where it satisfies the criteria of inserting.Here the criteria is values should not be empty and they should be unique.
if (!name && !mark ) {
document.getElementById("result").innerHTML = "No name or mark Has Been Entered. Please Try Again!";
}
else if (names.includes(nameInput.value) && mark.includes(markInput.value)) {
document.getElementById("result").innerHTML = "Name & Mark are same please enter again!";
}
else{
names.push(nameInput.value);
marks.push(markInput.value);
document.getElementById("result").innerHTML ="Name & Mark has successfully been entered!"
}
Alternatively you can also use object to achieve this.
Create an object having the name and mark as properties
let person = {name: name.value,mark: mark.value };
and push the object into the arr.
To check if the same name and mark are submitted use arr.find().
let name = document.getElementById("name");
let mark = document.getElementById("mark");
let arr = [];
const add = () => {
if (!name.value || !mark.value) {
alert("Please enter the value in both fields");
return;
}
let person = {
name: name.value,
mark: mark.value
};
if (arr.find(personIn => personIn.name == person.name && personIn.mark == person.mark)) {
alert("Please dont repeat the values");
return;
}
arr.push(person);
}
document.getElementById("submit").addEventListener('click', add);
Name:<input type="text" id="name" /><br> Mark:
<input type="text" id="mark" /><br>
<button id="submit">Submit</button>
<script>
$(document).ready(function() // Run the function after the DOM is ready
{
var validForm = true; // Set the variable to be true, assume the form is valid
// Required field. Cannot be empty, spaces, null or undefinded. Contents of the field cannot contain < or > or '.
function validateName()
{
var nameInput = $("#custName").val(); // Create a variable that takes in the value of the field
var nameEx = new RegExp(/<>^[a-zA-Z0-9]*$/); // RegEx of what the field should contain
var nameTest = nameEx.test(nameInput); // Test the RegEx with the current input
if(nameInput == "")
{
nameTest = false;
validForm = false; // Form will be set to false
var custNameError = $("#custNameError").html("Please enter a valid name");
}
else if (nameInput != "" && !nameTest)
{
nameTest = false;
validForm = false;
custNameError = $("#custNameError").html("Please enter a valid name");
}
else
{
custNameError = $("#custNameError").html("");
}
};
// Field is optional. Must be numbers only
function validatePhone()
{
var phoneInput = $("#custPhone").val();
var phoneEx = new RegExp(/^[0-9]{10}$/); // 10 digit RegEx from 0-9
if(phoneEx.test(phoneInput))
{
$("#custPhoneError").html("Please enter a valid 10 digit phone number");
validForm = false;
}
else
{
validForm = true;
}
};
// Required field. Can have letters, numbers, symbols, and including # and . email address.
function validateEmail()
{
var emailInput = $("#custEmail").val;
var emailEx = new RegExp (/^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$/);
var emailTest = emailEx.text(emailInput);
var custEmailError = $("#custEmailError").html("");
if(!emailTest)
{
validForm = false;
if(emailInput == "")
{
custEmailError = $("#custEmailError").html("Please enter a valid email address.");
}
else
{
if(emailInput != "" && !emailTest)
{
custEmailError = $("#custEmailError").html("Please enter a valid email in the following format: test123#email.com");
$("#custEmail").val(emailInput);
validForm = true;
}
}
}
};
// Required field. Must select one radio button
function validateProduct()
{
var productInput = $("input[type=radio]:checked").val();
if (productInput == undefined)
{
var productTest = false;
validForm = false;
var custProductError = $("#custProductError").html("Please select a product in regards to your complaint");
}
else if (!validForm)
{
$("input[type=radio]:checked").val(productInput);
}
else
{
productTest = true;
custProductError = $("#custProductError").html("");
validForm = true;
}
};
// Required field. Must be longer than 5 characters, can contain basic punctuation symbols
function validateComplaint()
{
var complaintInput = $("#custComplaint").val();
var complaintEx = new RegExp (/^[a-zA-Z0-9,.!?;" ]{5,}$/);
var complaintTest = complaintEx.test(complaintInput);
var complainLengthInput = complaintInput.length;
if (complainLengthInput < 5)
{
validForm = false;
var custComplaintError = $("#custComplaintError").html("Please have your complaint to be at least 5 characters long");
$("#custComplaint").val(complaintInput);
}
else if (complaintTest)
{
custComplaintError = $("#custComplaintError").html("");
}
else
{
if (complainLengthInput >= 5 && !complaintTest)
{
custComplaintError = $("#custComplaintError").html("Please describe your complaint in detail. Using letters and numbers.")
$("#custComplaint").val(complaintInput);
}
else
{
validForm = true;
}`enter code here`
}
};
function submitForm()
{
$("#sendForm").click(function()
{
validateName();
validateEmail();
validatePhone();
validateProduct();
validateComplaint();
});
$("#resetForm").click(function()
{
$("#custNameError").html("");
$("#custPhoneError").html("");
$("#custEmailError").html("");
$("#custProductError").html("");
$("#custComplaintError").html("");
});
};
});
HTML:
<h2>WDV321 Advanced Javascript </h2>
<h3>Form Validation Project - Complaint Form</h3>
<form id="form1" name="form1" method="post" action="">
<p>Please enter the following information in order to process your concerns.</p>
<p>
<label for="custName">Name:</label>
<input type="text" name="custName" id="custName" />
<span id="custNameError" class="errorMsg"></span>
</p>
<p>
<label for="custPhone">Phone Number: </label>
<input type="text" name="custPhone" id="custPhone" />
<span id="custPhoneError" class="errorMsg"></span>
</p>
<p>
<label for="custEmail">Email: </label>
<input type="text" name="custEmail" id="custEmail" />
<span id="custEmailError" class="errorMsg"></span>
</p>
<p>Please Select Product Group:</p>
<span class="error" id="custProductError"></span>
<p>
<label>
<input type="radio" name="custProducts" value="books" id="custProducts_0" />
Books</label>
<br />
<label>
<input type="radio" name="custProducts" value="movies" id="custProducts_1" />
Movies</label>
<br />
<label>
<input type="radio" name="custProducts" value="electronics" id="custProducts_2" />
Consumer electronics</label>
<br />
<label>
<input type="radio" name="custProducts" value="computer" id="custProducts_3" />
Computer</label>
<br />
</p>
<p>Description of problem: (Limit 200 characters)</p>
<span class="error" id="custComplaintError"></span>
<p>
I am extremely confused on what I am doing wrong. When the submit button is hit, it doesn't seems like its running any of my functions. The console on google chrome isnt giving me any errors, and from what I am reviewing, it doesnt seem like I see any syntax errors. Please advise.
function submitForm(e) // grab the click event
{
e.preventDefault(); // prevent default event
$("#sendForm").click(function()
{
validateName();
validateEmail();
validatePhone();
validateProduct();
validateComplaint();
});
$("#resetForm").click(function()
{
$("#custNameError").html("");
$("#custPhoneError").html("");
$("#custEmailError").html("");
$("#custProductError").html("");
$("#custComplaintError").html("");
});
};
When a user enters the below link in an input tag, I just want the last part of the string, in order to minimize input mistakes - the two input fields generate a new link that the user can copy and use.
name:id:5icOoE6VgqFKohjWWNp0Ac (I just want the last '5icOoE6VgqFKohjWWNp0Ac' part)
Can anyone help me with amending the below to achieve this?
function generateFullName() {
document.getElementById('txtFullName').value = ('https://nlproducts.nl/item/') + document.getElementById('fName').value + ('?context=') + document.getElementById('lName').value;
}
Enter a product ID:
<input type="text" id="fName" placeholder='0A5gdlrpAuQqZ2iFgnqBFW' />
Enter a user ID:
<input type="text" id="lName" oninput="generateFullName()" placeholder='37i9dQZF1DXcBWIGoYBM5M'/><br/></p>
Tada! This would be the link for your campaign:
<input type="text" id="txtFullName" name="txtFullName" />
Here's a JavaScript function that takes a string as input, and formats it to only keep the last part after the last colon (if it contains a colon):
function parseColon(txt) {
return txt.split(":").slice(-1).pop();
}
Eg. parseColon("a:b:c") would return "c"
You can validate your inputs with:
function isValidInput(txt) {
numberOfColons = txt.split(":").length - 1;
if (txt.length == 32 && numberOfColons == 2)
return true
return false
}
In your code you can use these two functions to check & parse lName and fName like this:
function generateFullName() {
var lName_val = document.getElementById('lName').value;
var fName_val = document.getElementById('fName').value;
//fill in link in the output if fName and lName are valid inputs
if(isValidInput(fName_val) && isValidInput(lName_val))
document.getElementById('txtFullName').value = ('https://nlproducts.nl/item/') + parseColon(fName_val) + ('?context=') + parseColon(lName_val);
// otherwise, clear the output field
else
document.getElementById('txtFullName').value = "";
}
function parseColon(txt) {
// return the part after the last colon
return txt.split(":").slice(-1).pop();
}
function isValidInput(txt) {
numberOfColons = txt.split(":").length - 1;
if (txt.length == 38 && numberOfColons == 2)
return true
return false
}
Enter a product ID:<br>
<input type="text" id="fName" oninput="generateFullName()" placeholder='0A5gdlrpAuQqZ2iFgnqBFW' size="50"/><br/>
Enter a user ID:<br>
<input type="text" id="lName" oninput="generateFullName()" placeholder='37i9dQZF1DXcBWIGoYBM5M' size="50"/><br/><br/>
Tada! This would be the link for your campaign:<br>
<input type="text" id="txtFullName" name="txtFullName" size="50"/>
I am working with a form and would like to print the user's input with the first letter of each word capitalized no matter how they type it in. For example, I want the user's "ronALd SmItH" to print as Rondald Smith. I would also like to do this for the address and city. I have read all of the similar questions and answers on here and they are not working for me. I am not sure if I am putting my code in the wrong place or what I'm doing wrong.
This is the code I am using:
function correctFormat(customer)
{
var first = customer.charAt(0).toUpperCase();
var rest = customer.substring(1).toLowerCase();
return first + rest;
}
I have tried placing that in a variety of places within the whole document, I have tried renaming the string (eg. name, city, address). I have also read the others postings on here with what seems like the same question as this but none are working. I am not entering a string that I want capitalized. The user is entering their data into a form and I need it to print in an alert in the correct format. Here is the above code within the entire document. I am sorry it is so long but I am again, at a loss.
<html>
<!--nff Add a title to the Web Page.-->
<head>
<title>Pizza Order Form</title>
<script>
/*nff Add the doClear function to clear the information entered by the user and enter the information to be cleared when the clear entries button is clicked at the bottom of the Web Page.*/
function doClear()
{
var elements = document.getElementsByTagName('select');
elements[0].value = 'PA';
document.PizzaForm.customer.value = "";
document.PizzaForm.address.value = "";
document.PizzaForm.city.value = "";
document.PizzaForm.state.value = "";
document.PizzaForm.zip.value = "";
document.PizzaForm.phone.value = "";
document.PizzaForm.email.value = "";
document.PizzaForm.sizes[0].checked = false;
document.PizzaForm.sizes[1].checked = false;
document.PizzaForm.sizes[2].checked = false;
document.PizzaForm.sizes[3].checked = false;
document.PizzaForm.toppings[0].checked = false;
document.PizzaForm.toppings[1].checked = false;
document.PizzaForm.toppings[2].checked = false;
document.PizzaForm.toppings[3].checked = false;
document.PizzaForm.toppings[4].checked = false;
document.PizzaForm.toppings[5].checked = false;
document.PizzaForm.toppings[6].checked = false;
document.PizzaForm.toppings[7].checked = false;
document.PizzaForm.toppings[8].checked = false;
return;
}
//nff Add a doSubmit button to indicate what the outcome will be when the user clicks the submit order button at the bottom of the form.
function doSubmit()
/*nff Add an if statement to the doSubmit function to return false if there is missing information in the text fields once the user clicks the submit order button.*/
{
if (validateText() == false) {
return false;
}
//nff Add an if statement to the doSubmit function to return false if there is no pizza size selected using the radio buttons.
if (validateRadio() == false) {
return false;
}
//nff Add an if statement to the doSubmit function to return false if there are no toppings selected using the checkboxes.
if (validateCheckbox() == false) {
return false;
}
//nff Add an if statement to the doSubmit function to return false if the email entered by the user is empty or does not fit the acceptable format.
if (validateEmail() == false) {
return false;
}
/*nff Add an if statement to the doSubmit function to return false if the phone number entered by the user is empty or does not fit the acceptable formats.*/
if (validatePhone() == false) {
return false;
}
if (validateZip() == false) {
return false;
}
//nff Add an alert box to show customer information from text fields when the Submit Order button is clicked.
var customer = document.PizzaForm.customer.value;
var address = document.PizzaForm.address.value;
var city = document.PizzaForm.city.value;
var state = document.PizzaForm.state.value;
var zip = document.PizzaForm.zip.value;
var phone = document.PizzaForm.phone.value;
var email = document.PizzaForm.email.value;
var size = "";
for (var i = 0; i < document.PizzaForm.sizes.length; i++) {
if (document.PizzaForm.sizes[i].checked) {
size = document.PizzaForm.sizes[i].nextSibling.nodeValue.trim();
break;
}
}
var toppings = [];
for (var i = 0; i < document.PizzaForm.toppings.length; i++) {
if (document.PizzaForm.toppings[i].checked) {
toppings.push(document.PizzaForm.toppings[i].nextSibling.nodeValue.trim());
}
}
alert("Name: " + customer + '\n' +
"Address: " + address + '\n' +
"City: " + city + '\n' +
"State: " + state + '\n' +
"Zip: " + zip + '\n' +
"Phone: " + phone + '\n' +
"Email: " + email + '\n' +
"Size: " + size + '\n' + (toppings.length ? 'Toppings: ' + toppings.join(', ') : ''));
}
//nff Add the validateText function to ensure that all text fields are complete before the order is submitted.
function validateText() {
var customer = document.PizzaForm.customer.value;
if (customer.length == 0) {
alert('Name data is missing');
document.PizzaForm.customer.focus();
return false
};
var address = document.PizzaForm.address.value;
if (address.length == 0) {
alert('Address data is missing');
return false;
}
var city = document.PizzaForm.city.value;
if (city.length == 0) {
alert('City data is missing');
return false;
}
var state = document.PizzaForm.state.value;
if (state.length == 0) {
alert('State data is missing');
return false;
}
var zip = document.PizzaForm.zip.value;
if (zip.length == 0) {
alert('Zip data is missing');
return false;
}
var phone = document.PizzaForm.phone.value;
if (phone.length == 0) {
alert('Phone data is missing');
return false;
}
var email = document.PizzaForm.email.value;
if (email.length == 0) {
alert('Email data is missing');
return false;
}
return true;
}
//nff Add the validateRadio function so that if none of the radio buttons for pizza size are selected it will alert the user.
function validateRadio() {
if (document.PizzaForm.sizes[0].checked) return true;
if (document.PizzaForm.sizes[1].checked) return true;
if (document.PizzaForm.sizes[2].checked) return true;
if (document.PizzaForm.sizes[3].checked) return true;
alert('Size of pizza not selected');
document.PizzaForm.sizes[0].foucs();
return false;
}
//nff Add the validateCheckbox function so that if none of the checkboxes for toppings are selected it will alert the user.
function validateCheckbox() {
if (document.PizzaForm.toppings[0].checked) return true;
if (document.PizzaForm.toppings[1].checked) return true;
if (document.PizzaForm.toppings[2].checked) return true;
if (document.PizzaForm.toppings[3].checked) return true;
if (document.PizzaForm.toppings[4].checked) return true;
if (document.PizzaForm.toppings[5].checked) return true;
if (document.PizzaForm.toppings[6].checked) return true;
if (document.PizzaForm.toppings[7].checked) return true;
if (document.PizzaForm.toppings[8].checked) return true;
alert ('Toppings are not selected');
return false;
}
//nff Add the validateEmail function to ensure that the email address has been entered in the correct format.
function validateEmail() {
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{3,4})+$/.test(PizzaForm.email.value))
{
return (true)
}
alert("You have entered an invalid email address")
return (false)
}
//nff Add the validatePhone function to ensure that the phone number has been entered in any of the acceptable formats.
function validatePhone() {
if (/^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/.test(PizzaForm.phone.value))
{
return (true)
}
alert("You have entered an invalid phone number")
return (false)
}
function validateZip() {
if (/^\d{5}([\-]\d{4})?$/.test(PizzaForm.zip.value))
{
return (true)
}
alert("You have entered an invalid zip")
return (false)
}
function correctFormat(customer)
{
var first = customer.charAt(0).toUpperCase();
var rest = name.substring(1).toLowerCase();
return first + rest;
}
</script>
</head>
<body>
<!--nff Add a form for the user to enter information into.-->
<form name="PizzaForm">
<!--nff add a title at the top of the Web Page-->
<h1>The JavaScript Pizza Parlor</h1>
<!--nff add directions to the user for the information to be entered-->
<p>
<h4>Step 1: Enter your name, address, and phone number:</h4>
<!--nff change the font-->
<font face="Courier New">
<!--nff insert a text field for user to enter their name, add spaces between the title of the text box and the box itself, specify the size of the input box, and the type of input into the box as text.-->
Name: <input name="customer" size="50"
type="text"><br>
<!--nff insert a text field for user to enter their address, specify the size of the input box, and the type of input into the box as text.-->
Address: <input name="address" size="50" type="text"><br>
<!--nff Insert a text field for user to enter their city, add spaces between the title of the text box and the box itself, specify the size of the input box, and the type of input into the box as text.-->
City: <input name="city" size="15" type="text">
<!--nff Insert text fields for the user to enter their state and zip, specify the sizes of the input boxes, and specify that the text to be entered into the boxes will be in all caps for the state box. These input boxes should be on the same line as the last one.-->
State:<select name="state">
<option selected value="PA">PA</option>
<option value="NJ">NJ</option>
<option value="NY">NY</option>
<option value="DE">DE</option>
</select>
Zip: <input name="zip" size="5" type="text"><br>
<!--nff Insert a text field for the user to enter their phone number, insert spaces after the title of the box, specify the size of the box, and the type of input as text.-->
Phone: <input name="phone" size="50" type="text"><br>
<!--nff Insert a text field for the user to enter their email address, insert spaces after the title of the box, specify the size of the box, and the type of input as text.-->
Email: <input name="email" size="50" type="text"><br>
</font>
</p>
<!--nff add second step to order a pizza-->
<p>
<h4>Step 2: Select the size of pizza you want:</h4>
<font face="Courier New">
<!--nff Add radio buttons to choose from four options for pizza sizes.-->
<input name="sizes" type="radio" value="small">Small
<input name="sizes" type="radio" value="medium">Medium
<input name="sizes" type="radio" value="large">Large
<input name="sizes" type="radio" value="jumbo">Jumbo<br>
</font>
</p>
<p>
<!--nff add third step to order a pizza-->
<h4>Step 3: Select the pizza toppings you want:</h4>
<font face="Courier New">
<!--nff Add check boxes for user to choose toppings.-->
<input name="toppings" type="checkbox" value="pepperoni">Pepperoni
<input name="toppings" type="checkbox" value="canadian bacon">Canadian Bacon
<input name="toppings" type="checkbox" value="sausage">Sausage<br>
<input name="toppings" type="checkbox" value="mushrooms">Mushrooms
<input name="toppings" type="checkbox" value="pineapple">Pineapple
<input name="toppings" type="checkbox" value="black olives">Black Olives<br>
<input name="toppings" type="checkbox" value="green peppers">Green Peppers
<input name="toppings" type="checkbox" value="extra cheese">Extra Cheese
<input name="toppings" type="checkbox" value="none">None<br>
</font>
</p>
<!--nff Add buttons for the options to submit order or clear entries. Add an onClick event to show one of the alerts entered earlier in this document when the submit button is clicked at the bottom of the Web Page. Add and onClick event to clear the entries in this form upon clicking the clear entries button.-->
<input type="button" value="Submit Order" onClick="doSubmit()">
<input type="button" value="Clear Entries" onClick="doClear()">
</form>
</body>
</html>
You can use regular expression, such as this:
function correctFormat(customer){
return customer.replace(/\b(.)(.*?)\b/g, function(){
return arguments[1].toUpperCase() + arguments[2].toLowerCase();
});
}
Your function only capitalizes the first letter of the string but not the first letter of each word. You can try splitting the string into separate words using string.split(' '):
function correctFormat(customer)
{
if (customer == null || customer.length == 0)
return customer;
var words = customer.split(/\s+/g);
for (var i = 0; i < words.length; ++i) {
var first = words[i].charAt(0).toUpperCase();
var rest = words[i].substring(1).toLowerCase();
words[i] = first + rest;
}
return words.join(' ');
}
I also noticed that you do not call correctFormat anywhere. You need to call the function in order for it to be executed. For example:
var customer = correctFormat(document.PizzaForm.customer.value);
As mentioned by #Wee You, you use customer for the first letter but use name for the rest letters. You have to call this function with user inputs and then update text in dom with the correct format.
function correctFormat(str)
{
var first = str.charAt(0).toUpperCase();
var rest = str.substring(1).toLowerCase();
return first + rest;
}
Here's a tiny example of the code you need:
Pass to the .replace() method every name part:
var PizzaForm = document.PizzaForm;
var customer = PizzaForm.customer;
function formatName() {
this.value = this.value.replace(/([^ \t]+)/g, function(_, str) {
var A = str.charAt(0).toUpperCase();
var bc = str.substring(1).toLowerCase();
return A + bc;
});
}
customer.addEventListener("input", formatName);
<form name="PizzaForm">
Name: <input name="customer" size="50" type="text">
</form>
the above will work also on Paste. Have fun
PS: instead of all that doClear(){ wall of code, why don't you reset your form by simply using: PizzaForm.reset();
Try this function
function correctFormat(customer)
{
var upperText = customer.toLowerCase();
var result = upperText.charAt(0).toUpperCase();
for(var i=1;i<upperText.length;i++)
if(upperText.charAt(i-1) == ' ')
result += upperText.charAt(i).toUpperCase();
else
result += upperText.charAt(i);
return result;
}
i am trying to learn html and javascript. I have created an html form and am using javascript to validate the fields. I have a isNaN check for the age field, a regex check for emial and a presence check for all fields. I am currently outputting the form to the address bar but this does not work as i am getting errors.
<title> </title>
<script type="text/javascript">
function validate()
{
var errors = 0;
if (isNumeric(document.getElementById("age").value) == false)
{
errors++;
}
if (emailCheck(document.getElementById("email").value) == false)
{
errors++;
}
var inputBoxes = document.getElementsByTagName('input');
for(var i= 0; i < inputBoxes.length; i++)
{
if(inputBoxes[i].type != 'text') continue;
if(presenceCheck(inputBoxes[i].value) == false)
{
errors++;
}
}
console.log(errors);
if(errors == 0)
{
window.location.assign("output.html#" + "%%" + "name" + "%%" +
document.getElementById("name").value + "%%" + "email" + "%%" +
document.getElementById("email").value + "%%" + "age" + "%%" +
document.getElementById("age").value + "%%" + "comments" + "%%" +
document.getElementById("comments").value);
}
}
function isNumeric(number)
{
return !isNaN(number) && number != null && number != "";
}
function emailCheck(email)
{
var emailRegex = /\s+#\s+.\s+/;
return emailRegex.test(email);
}
function presenceCheck(data)
{
var regex = /\s+/;
return regex.test(data);
}
</script>
Below is the form which is just incased in body tags at the moment
<form id="frmA" name="frmA">
<label name="frmName">Name:</label><br />
<input form="frmA" type="text" name="frmName" id="name"/><br />
<label name="frmEmail">E-Mail:</label><br />
<input form="frmA" type="text" name="frmEmail" id="email"/><br />
<label name="age">Age:</label><br />
<input form="frmA" name="frmAge" id="age"/><br />
<label name="frmComments">Comments:</label><br />
<textarea form="frmA" cols="50" rows="10" id="comments"></textarea><br />
</form>
<button onClick="validate();">Submit</button>
i know that the checks work when no data is present however when i input data in the form and hit submit i am still faced with 4 errors. (there are 5 errors with no data: 3x presence checks, 1 for the regex and one for the isNaN)
My question therefore is why am i still getting errors and why do i get no output.
Any help would be greatly appreciated.
Extra: i would also like the input fields to change colour when there is an error.
Your regexes are wrong. You have /\s+#\s+.\s+/ and it should be /\w+#\w+\.\w+/. You didn't escape the dot and \s matches whitespace, not strings. \w matches word. For a proper email regex you would need much more than that but for your simple case to work this will suffice. The second regex should be /\w+/.