My validation and the push() is not working - javascript

The user has to type the information in a text box and then click on the button to add the names. If the format is correct the name will appear below the text box. If the format is incorrect a message will be generated that reads "Incorrect Format".
The users inputs will create a list of names that will appear underneath the text box.
function validate(name){
var str = [];
var name = document.getElementById("letters");
var check = /^[A-Za-z]+$/;
if(name.value.match(check)){
str.push(document.getElementById("letters"));
document.write("Name: " + name);
}
else{
document.write("Incorrect Format");
}
}
validate();

I think this is what you're trying to achieve:
function validate() {
console.clear();
var check = /^[A-Za-z]+$/;
var inputVal = document.getElementById('letters').value;
if (inputVal.match(check)) {
console.log("Name: " + inputVal);
document.getElementById('container').innerHTML += inputVal + "<br/>";
} else {
console.log("Incorrect Format");
}
}
document.getElementById('btnValidate').addEventListener('click', validate);
<input type="text" id="letters" />
<input type="button" id="btnValidate" value="Validate" />
<div id="container"></div>

Related

how to add n number of input fields in html using js

I have to get 'n' - total number of names from the user and then create n number of fields for getting all the names. I've currently written this as:
HTML code:
<form action="/flight_ticket/book" name="myform" method="post">
.
.
.
Enter the number of tickets to be booked:
<input name="nooftickets" type="text"><br/><br/>
Enter names
<div id='container'/>
</div>
<br/><br/>
</form>
</body>
JS code:
function addFields(){
var number = parseInt(document.getElementById("nooftickets").value);
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
container.appendChild(document.createTextNode("Name " + (i+1)));
var input = document.createElement("input");
input.type = "text";
input.name = "name" + i;
//input.required= true;
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
But when I run it on browser, after clicking the "Enter names", I don't see any changes in the browser!
What have I got wrong?
What you are doing is trying to fetch the value of the noofticktes which is defined as a name in the HTML but in your code, you are using document.getElementById('noofticktes').value which is throwing an undefined error as there is no id defined as noofticktes.
So, just change your code on from:
var number = document.getElementById("nooftickets").value;
To this:
var number = document.getElementsByName("nooftickets")[0].value;
you will be able to make your code work.
One small update in your code would be if you are trying to clear/remove all the contents of the element container just use the container.innerHTML='' instead of looping and removing each element.
Here is the updated Snippet of your code.
function addFields() {
debugger;
var number = document.getElementsByName("nooftickets")[0].value;
var container = document.getElementById("container");
container.innerHTML = '';
for (i = 0; i < number; i++) {
container.appendChild(document.createTextNode("Name " + (i + 1)));
var input = document.createElement("input");
input.type = "text";
input.name = "name" + i;
//input.required= true;
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
<form action="/flight_ticket/book" name="myform" method="post">
. . . Enter the number of tickets to be booked:
<input name="nooftickets" type="text"><br/><br/>
Enter names
<div id='container' />
</div>
<br/><br/>
</form>
function addFields() {
// body...
var input = '';
var number = document.getElementById('number').value;
for(var i=0;i<number;i++)
{
input +="<input id='number"+i+"' name='number"+i+"'><br>";
}
document.getElementById('container').innerHTML = input;
}
<form action="/flight_ticket/book" name="myform" method="post">
Enter the number of tickets to be booked:
<input name="nooftickets" id="number" type="text"><br/><br/>
Enter names
<div id='container'/>
</div>
<br/><br/>
</form>

Concatenating to user input

An example would be if I type !greet it would output "Hello username".
The end goal is to integrate this into a discord bot.
An example of what I have tried:
function doGreeting() {
var input = document.getElementById('userInput')
alert(input);
}
if (msg.content === prefix + 'greet') {
msg.channel.sendMessage('Hello ' + doGreeting())
};
I don't know about your input field id or class but I am giving you example below so it may help you.
<input type="text" id="my_id" >
<span id="msg"></span>
<script>
var input_val = document.getElementById("my_id");
if(input_val .indexOf("!greet") !=-1){ // if there is !greet word
var split_str = input_val .split(" ");
document.getElementById('msg').innerHTML = "Hello "+split_str [1];
}
</script>

Why doesn't my reset() function remove my red error lines?

function validate() {
var fname = document.getElementById("fname").value;
document.getElementById("errorfname").innerHTML = "";
if (checkfname() == true) {
alert("Entry submitted.");
} else {
return false;
}
}
function checkfname() {
var fname = document.getElementById("fname").value;
if (fname.length == 0) {
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot be empty.";
return false;
} else if (!isNaN(fname)) {
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot contain numbers.";
return false;
} else {
return true;
}
}
function addRow() {
if (validate() == true) {
}
}
<form>
First Name:
<input type="text" id="fname" name="fname" />
<p id="errorfname" class="red"></p>
<input id="submit" type="submit" value="Submit Entry" onclick="return addRow()" />
<input id="clear" type="button" value="Reset" onclick="reset()" />
</form>
<form>
<fieldset>
<label for = "firstnameinput">
First Name: <input type = "text" id = "fname" name = "fname" placeholder = "John"/>
<p id = "errorfname" class = "red"></p>
</label>
</fieldset>
<fieldset>
<label id = "submitbutton">
<input id = "submit" type = "submit" value = "Submit Entry" onclick = "return addRow();upperCase();"/>
</label>
<label id = "resetbutton">
<input id = "clear" type = "button" value = "Reset" onclick = "reset()"/>
</label>
</fieldset>
</form>
This is my simplified HTML file. It basically has an input and a paragraph below it to display an error message later on. For now it is set as "" in javascript. The HTML also has a submit button and a reset button. The purpose of the reset button is to clear all previously entered fields or any error message that has appeared.
function validate(){
var fname = document.getElementById("fname").value;
document.getElementById("errorfname").innerHTML = "";
if(checkfname() == true){
alert("Entry submitted.");
}
else{
return false;
}
function checkfname(){
var fname = document.getElementById("fname").value;
if(fname.length == 0) {
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot be empty.";
return false;
}
else if(!isNaN(fname)){
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot contain numbers.";
return false;
}
else{
return true;
}
}
function addRow(){
if(validate() == true){
event.preventDefault();
var fname = document.getElementById("fname").value;
firstNameArray.push(fname)
var row = document.getElementById('table').insertRow(-1);
var colNum = row.insertCell(0);
var colName = row.insertCell(1);
i++;
colNum.innerHTML = i;
colName.innerHTML = fname + " " + lname;
else{
return false;
}
reset();
}
Lastly, my reset() function below.
function reset(){
document.getElementById("errorfname").innerHTML = "";
document.getElementById("fname").value = "";
}
The problem is, for example, in the input box for fname, I enter John. When I press the reset button on my HTML which calls the reset() function, John in the box disappears so I got that going for me which is nice. However, lets say I purposely left the box blank to receive an error message, a red sentence below the box appears saying "Invalid first name. Cannot be empty." When I press the reset button to call onto the reset() function, this red error message does not disappear however, any current value inside the box disappears. This makes by reset() function work 50% only. I clearly stated for both to disappear in my reset() function.
TL;DR
I have a reset button in my HTML which calls a reset() function in my javascript. I have a name input box in my HTML and what the reset() function is supposed to do is to remove any current name which is inside the box as well as remove any error message that appears below. My reset() function is able to clear away any name inside the box currently but is unable to clear away the error message.
I created a fiddle to test your problem. I noticed the same thing. I changed the method reset() to resetTest() and it worked fine.
working fiddle
The reason changing the name worked is that onxyz= attribute event handlers are run (effectively) within a couple of with statements, one of which is with (theEnclosingFormElement). Form elements have a built-in reset method that clears all of their inputs to their initial values. So in this:
<input id = "clear" type = "button" value = "Reset" onclick = "reset()"/>
The reset being called isn't your reset, it's the form's reset, which doesn't (of course) do anything with errorfname. Changing the name removes the conflict.

How can i add a bulleted list to my java script code. Also how do i center the the user input like <center> but in javascript

i would like to know how i can make it so when people input something it goes in a bulleted list, in the middle of the screen. Like but in javascript?
I got my code from: How to display input back to the user on an HTML page?
<html><head></head><body>
<input id="title" type="text" maxlength="276" onkeyup="Allow()" >
<input type="submit" value="Save/Show" onclick="insert()" />
<div id="display"></div>
<script type="text/javascript">
var titles = [];
var titleInput = document.getElementById("title");
var messageBox = document.getElementById("display");
function Allow(){
if (!user.title.value.match(/[a-zA-Z1-9]$/) && user.title.value !="") {
user.title.value="";
alert("Please Enter only alphabets");
}
}
function insert () {
titles.push(titleInput.value);
clearAndShow();
}
function clearAndShow () {
titleInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += "To Do: " + titles.join(", ") + "<br/>";
}
</script>
</body>
</html>
jsbin example: https://jsbin.com/xahidolibu/edit?html,output
I've modified your code to:
create a list instead of comma deliminated string on clearAndShow()
added css to center align the list
jsbin: https://jsbin.com/lamebopidu/1/edit?html,css,output

How do I print user input with the first letter of each word capitalized?

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;
}

Categories