I am trying to use the ErrorFoundFlag approach to Show an error message for all fields that are in error at once.
I have tried:
function processInfo() {
var errorFoundFlag = "N"; //Initialize variable to 'N'
firstName = $("firstname").value;
lastName = $("lastname").value;
numPets = $("numpets").value;
var message = "";
if (firstName >= 0) {
firstName = firstname.length;
msg += "Please enter first name";
errorFoundFlag = "Y";
}
if (lastName >= 0) {
lastName = lastname.length;
msg += "Please enter last name";
errorFoundFlag = "Y";
}
if (numPets >= 0) {
numPets = numpets.length;
msg += "Please enter the number of pets you have";
errorFoundFlag = "Y";
}
}
<p>
Enter First Name: <input type="text" id="firstname" />
<span id="firstname_error"></span>
</p>
<p>
Enter Last Name: <input type="text" id="lastname" />
<span id="lastname_error"></span>
</p>
<p>
How Many Pets do you have? (0-3):
<input type="text" id="numpets" size="1" maxlength="1" />
<span id="numpets_error"></span>
</p>
I need the error message to appear next to the input boxes when no text is input. And when text is input, the error message should go away but it's not working for me.
for example:
if the
Enter First Name: is blank... (Please Enter First Name) Would Appear
but if the name is entered the error message should go away. and if the other two are blank but the first name is entered when they click submit there would be error messages showing for the ones left blank.
There are several issues, but making the minimum number of changes to get roughly what you're asking for could look something like the following.
First, to get the value with jQuery you'll want val() (instead of value): $("#firstname").val().
Then simple references to the error spans (for example: $("#firstname_error")). These are cleared every time so the errors go away.
Then comparing the values length to 0 (note this could still be buggy, for example, an empty space would pass: " ").
Then console logging the errorFoundFlag to do as you need.
Finally, calling this method on each input change with onchange.
There are a number of improvements that can be made, but these were the minimum number of changes to get what you had working.
function processInfo() {
var errorFoundFlag = "N"; //Initialize variable to 'N'
firstName = $("#firstname").val()
lastName = $("#lastname").val();
numPets = $("#numpets").val();
firstNameError = $("#firstname_error");
lastNameError = $("#lastname_error");
numPetsError = $("#numpets_error");
firstNameError.text("")
lastNameError.text("")
numPetsError.text("")
if (firstName.length === 0) {
firstNameError.text("Please enter first name");
errorFoundFlag = "Y";
}
if (lastName.length === 0) {
lastNameError.text("Please enter last name");
errorFoundFlag = "Y";
}
if (numPets.length === 0) {
numPetsError.text("Please enter the number of pets you have");
errorFoundFlag = "Y";
}
console.log(errorFoundFlag)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
Enter First Name: <input type="text" id="firstname" onchange="processInfo()" />
<span id="firstname_error"></span>
</p>
<p>
Enter Last Name: <input type="text" id="lastname" onchange="processInfo()" />
<span id="lastname_error"></span>
</p>
<p>
How Many Pets do you have? (0-3):
<input type="text" id="numpets" size="1" maxlength="1" onchange="processInfo()" />
<span id="numpets_error"></span>
</p>
Related
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"/>
Goal:
Phone number must be entered in this format, 208-111-1111; otherwise it shows the error message.
What is the best way to show the error message when the user entered in the correct format but if the user re-entered in the correct format, the error message will disappear.
JS
phoneNumber = document.getElementById("phone");
var result = phoneNumber.toString().match(/^\d{3}-\d{3}-\d{4}$/);
function validatePhone(){
if (result == null)
{
error2.innerHTML = "The number is not in a correct format";
} else
{
error2.innerHTML = " ";
};
}
HTML
<p>Phone:</p>
<input type = "text" id="phone" name="phone" onChange="validatePhone()">
<br>
<span id="error2" ></span>
function validatePhone() {
phoneNumber = document.getElementById("phone");
var result = phoneNumber.value.match(/^(\d{3}-\d{3}-\d{4})?$/);
if (result == null) {
error2.innerHTML = "The number is not in a correct format";
} else {
error2.innerHTML = " ";
};
}
<p>Phone:</p>
<input type="text" id="phone" name="phone" oninput="validatePhone()">
<br>
<span id="error2"></span>
The problem is with the phoneNumber.toString() call.
Calling toString() on a DOM input element does not return the value of the user input. toString() is intended to provide a string representation of the object it is called on, not retrieve a value held by the object.
phoneNumber.value will return the value you are looking for.
id like my "Invalid contact number" to show if the text field is empty or if it does not contain 11 digits (if the text field has content)
HTML:
<label id="number_label">
<b>Contact Number</b>
</label>
<input type="text" placeholder="Contact Number" class="form-control" id="contact" name="contact">
Javascript:
var contact = document.getElementById("contact").value;
if (!contact || (contact.val().length >=12 || contact.val().length <=10) ) {
document.getElementById("number_label").innerHTML = "<span style='color: red;'>Invalid contact number (must contain 11 digits)</span>";
} else {
document.getElementById("number_label").innerHTML = "Contact Number";
}
My "number_label" id in the if statement should change text and display the error.
It isn't working
You're calling .val() on contact (a String) which is no good. .val() is a jQuery method, and is meant to be called on the element itself.
the form just loads the "Invalid contact number" and reloads the page going back to the beginning
If you're trying to restrict a form from posting, make sure any path in your function that should restrict this has a return false.
var label = document.getElementById("number_label");
function validate() {
var contact = document.getElementById("contact").value;
if (!contact || contact.length !== 11) {
label.innerHTML = "<span style='color: red;'>Invalid contact number (must contain 11 digits)</span>";
return false;
} else {
label.innerHTML = "<b>Contact Number</b>";
}
}
<label id="number_label">
<b>Contact Number</b>
</label>
<input type="text" placeholder="Contact Number" class="form-control" id="contact" name="contact">
<button onclick="validate()">Validate</button>
Your code has some errors. val() is not a function of the element.
if (!contact || (contact.**val()**.length >=12 || contact.**val()**.length <=10) ) {
Follows a fiddle with the code fixed. link
I create a multiphase form (wizards from) and I want to show in the last step all Information in input text (you can modify it) before validate
I try a lot but without any result, how can I do it ?
My code
var fname, lname, age;
function _(x) {
return document.getElementById(x);
}
function processPhase1(){
fname = _("firstname").value;
lname = _("lastname").value;
if(fname.length > 2 && lname.length > 2){
_("phase1").style.display = "none";
_("phase2").style.display = "block";
}
else {alert("Please Enter All Information");}
}
function processPhase2(){
age = _("age").value;
if(age.length >= 1){
_("phase2").style.display = "none";
_("show_info").style.display = "block";
}
else {alert("Please Enter All Information");}
}
<body>
<div id="phase1">
First Name : <input id="firstname" name="firstname"><br>
Last Name : <input id="lastname" name="lastname"><br>
<button onclick="processPhase1()">Next</button>
</div>
<div id="phase2">
Age : <input id="age" name="age"><br>
<button onclick="processPhase2()">Next</button>
</div>
<div id="show_info">
First Name : <input id="firstname" name="firstname" value = ""><br>
Last Name : <input id="lastname" name="lastname" value = ""><br>
Age : <input id="age" name="age" value = ""><br>
<button onclick="submit()">submit</button>
</div>
I try this but it's just for showing Information, but you can't modify it, I need to show it in input text
function processPhase2(){
age = _("age").value;
if(age.length >= 1){
_("phase2").style.display = "none";
_("show_info").style.display = "block";
_("display_fname").innerHTML = fname;
_("display_lname").innerHTML = lname;
_("display_age").innerHTML = age;
}
else {alert("Please Enter All Information");}
}
<div id="show_info">
First Name : <span id="display_fname"></span><br>
Last Name : <span id="display_lname"></span><br>
Age : <span id="display_age"></span><br>
<button onclick="submit()">submit</button>
</div>
I would have done this completely different, but this is how you would do it based on what you've already written. When you click the next button in each function, you want to grab that value of (fname, lname, or age) and set the value of that to the value of the last set of inputs. I've altered your code a bit and made you a JS BIN http://jsbin.com/sopikuzuri/edit?html,output
In simple terms
Each time you call a new phase function (processPhase1), you want to grab the values of what the user just entered.
Then, you want to set those values to the proper <input />
So, the simplest example I can give is this:
Below, the user will enter some data into the field. When they click the submit phase 1 button we will grab the value of what they just entered and set that value to the last input (for them to see/edit)
<input type="text" id="firstName"/>
<button id="submit">Submit Phase 1</button>
<input type="text" id="displayInput"/>
<script>
$("#submit").click(function() {
// getting the value of what the user typed in
var fname = $("#firstName").value;
// setting the value of the final box to the var above
$("#displayInput").val(fname);
});
</script>
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;
}