Custom Form Validation Messages - javascript

Hey everyone reading this!
I am trying to validate a form and have that text field showing in case something's left empty. It does show indeed but too many time and I can't figure out why the counter doesn't work. Open to any ideas ... Thanks!
// For checking if the fields are filled and creating an html element
var newP = document.createElement("p");
var alertText = document.createTextNode("You should fill both fields!");
newP.appendChild(alertText);
var counter = 0;
// Declaring the canvas
var canvas = document.getElementById("draw");
var ctx = canvas.getContext('2d');
var formValue = document.getElementById("gameForm");
var submit = document.querySelector("#submitGameForm");
submit.addEventListener('click', function(e){ e.preventDefault(); validateForm();});
//global machen
function validateForm(){
var name = document.getElementById("name").value;
var hours = document.getElementById("hours").value;
var expressionName = new RegExp("^[a-zA-Z\s]+$");
var expressionHours = new RegExp("[0-9 ]+");
var correct = true;
var showMessage = false;
//Test if empty
if(name == "" || name == null || hours == "" || hours == null){
showMessage= true;
correct= false;
}
if(showMessage && counter == 0){
formValue.appendChild(newP);
console.log(newP);
counter++;
}
if(!expressionName.test(name)) {
document.getElementById("name").style.background='#8e3733';
correct = false;
}
else{
document.getElementById("name").style.background='#FFFFFF';
}
if(!expressionHours.test(hours)) {
document.getElementById("hours").style.background='#8e3733';
correct = false;
}
else{
document.getElementById("hours").style.background='#FFFFFF';
}
}
<main class="game" id="mainIndex">
<div class= "divGameForm">
<h2>Confess in order to play</h2>
<form id="gameForm">
<label for="name">Enter your name:</label>
<input id="name" type="text" >
<label for="hours">How many hours per day do you spend playing?</label>
<input id="hours" type="text" >
<p>Press the button if you would like to increase them!</p>
<input id="submitGameForm" type="submit" value="Submit" >
</form>
</div>
<div class="divGame">
<canvas id="draw"> </canvas>
<div>
<p>You can only draw circles. The dimentions are 240 (width) and 300 (height). Try it out!s</p>
<label for="xPos">Enter value for x: </label>
<input id="xPos" type="text">

You can use the counter In the test scenario empty as counter++ then should change showmessage and counter > 0
var newP = document.createElement("p");
var alertText = document.createTextNode("You should fill both fields!");
newP.appendChild(alertText);
var counter = 0;
// Declaring the canvas
var canvas = document.getElementById("draw");
var ctx = canvas.getContext('2d');
var formValue = document.getElementById("gameForm");
var submit = document.querySelector("#submitGameForm");
submit.addEventListener('click', function(e) {
e.preventDefault();
validateForm();
});
//global machen
function validateForm() {
var name = document.getElementById("name").value;
var hours = document.getElementById("hours").value;
var expressionName = new RegExp("^[a-zA-Z\s]+$");
var expressionHours = new RegExp("[0-9 ]+");
var correct = true;
var showMessage = false;
//Test if empty
if (name == "" || name == null || hours == "" || hours == null) {
showMessage = true;
correct = false;
counter++;
}
if (showMessage && counter > 0) {
formValue.appendChild(newP);
console.log(newP);
}
if (!expressionName.test(name)) {
document.getElementById("name").style.background = '#8e3733';
correct = false;
} else {
document.getElementById("name").style.background = '#FFFFFF';
}
if (!expressionHours.test(hours)) {
document.getElementById("hours").style.background = '#8e3733';
correct = false;
} else {
document.getElementById("hours").style.background = '#FFFFFF';
}
}

Related

Basic Javascript onclick

here's my code, brand new to coding trying to get the box "points" to return the sum of pointSum if "Ben" is typed into the box "winner". Just trying to work on some basics with this project. Attempting to make a bracket of sorts
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
if (winnerOne = true){
pointSum+=firstRound
} else if (winnerTwo = true){
pointSum+=secondRound
} else if (winnerThree = true){
pointSum+=thirdRound
} else if (winnerFour = true){
pointSum+=fourthRound
} else if (winnerFive = true){
pointSum+=fifthRound
} else if (winnerSix = true){
pointSum+=finalRound
else
function tally() {if document.getElementById('winner') == "Ben" { winnerOne = true;
}
pointSum=document.getElementById("points").value;
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
</body>
</html>
UPDATE***** new code, getting better, not returning console errors but still not getting anything in the "points" box upon clicking tally
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
function tally() {
var winner = document.getElementById("winner").value;
var firstWinner = "Ben";
if (winner == firstWinner){
winnerOne == true;
}
pointSum = document.getElementById("points").value;
}
if (winnerOne == true){
pointSum+=firstRound;
} else if (winnerTwo){
pointSum+=secondRound;
} else if (winnerThree){
pointSum+=thirdRound;
} else if (winnerFour){
pointSum+=fourthRound;
} else if (winnerFive){
pointSum+=fifthRound;
} else if (winnerSix){
pointSum+=finalRound;
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
<div class="updatePoints">
</div>
</body>
</html>
Your code has a few mistakes, lets change it a little bit!
First, you need to access 'value' atribbute of your winner element in your if statement, and surround all the statement in parenthesis
function tally() {
if (document.getElementById('winner').value == "Ben"){
winnerOne = true;
}
pointSum = document.getElementById("points").value;
}
Second, you use '==' to make comparison, you are using '=', it means that you are assign true to variables, and you're forgetting to put ';' at the end of lines! change this part:
if (winnerOne == true){
pointSum+=firstRound;
}
put all of your if/else like the example above!
Hint: when you are using if statement you can use like this:
if (winnerOne){ //you can omit == true, because if winnerOne is true, it will enter ind the if statement
//will enter here if winnerOne is true
}
if (!winnerOne){ //you can omit == false, because if winnerOne is not true, it will enter ind the if statement
//will enter here if winnerOne is false
}
You also have a left over else at the end of your if check which is invalid. You need to end the last else if statement with the };.
Are you trying to out put the text somewhere? I don't see any code that is handling this - you may want to add some HTML that will update like so:
<div class="updatePoints">
// leave empty
</div>
Then within your JavaScript you can always add some code to update the .updatePoints
var points = document.getElementByClass('updatePoints');
points.innerHTML = pointSum.value;
Have add some lines in your code and modify it with some comments. Can try at https://jsfiddle.net/8fhwg6ou/. Hope can help.
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
function tally() {
var winner = document.getElementById("winner").value;
var firstWinner = "Ben";
if (winner == firstWinner){
winnerOne = true; // Use only one = symbol to assign value, not ==
pointSum = Number(document.getElementById("points").value); // moved from outside and convert to number
// This code will update point in Points box
document.getElementById("points").value = tally_pointsum(pointSum);
// The codes below will add the text in div, just remove the + sign if you don't like
document.getElementById("updatePoints").innerHTML += (tally_pointsum(pointSum) - pointSum) + " points added<br />";
}
}
// Wrap codes below become a function, lets call it tally_pointsum:
function tally_pointsum(pointSum) {
if (winnerOne == true){
pointSum+=firstRound;
} else if (winnerTwo){
pointSum+=secondRound;
} else if (winnerThree){
pointSum+=thirdRound;
} else if (winnerFour){
pointSum+=fourthRound;
} else if (winnerFive){
pointSum+=fifthRound;
} else if (winnerSix){
pointSum+=finalRound;
}
return pointSum; //return the sum to caller
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
<!-- change class="updatePoints" to id="updatePoints" for document.getElementById("updatePoints") -->
<div id="updatePoints">
</div>
Happy coding.

How can I set a variable to a text input and then make it appear on screen

I am making a text based game for school and I am stuck with trying to set a variable as an text input. What I would like to happen is the player type start into the input and it do what is inside of the if statement. However from there I would like the player to enter a username and then it set the variable of "name" to what they input but with out it saving the name as "start".
//js
var name = "";
var beginBeenTo = false;
if (beginBeenTo == false) {
if (input == "START") {
beginBeenTo = true;
page = page + 1;
healthPoints = 25;
soundEveningBreeze.play();
$("#welcome_message").show().insertBefore("#placeholder").delay(3000).fadeOut(3000);
$("<br><p class='text'>You there, what is your name?</p>").hide().insertBefore("#placeholder").delay(7000).fadeIn(3000);
if (input != "" || namingBeenTo == false) {
name = input;
}
}
}
document.getElementById("print_name").innerHTML = name;
Quite simply, watch for some event (keyup in my case), check if the input value is START, if so ask for a username.
var started = false;
var username = '';
$('input').on('keyup', function(){
var tmpValue = $(this).val();
if(started){
username = tmpValue
}
if(tmpValue === 'START') {
started = true;
$(this).val('')
$(this).attr('placeholder','Username')
}
$('#username').text(username)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span id="username"></span>
<br>
<input type="text" placeholder="Type START to play">
it could be done with use of function like this :
var name = "";
$("form").submit(function() {
var input = $("#command_input").val().toUpperCase();
if (input == "START") {
name = $("#input_form").val();
}
}
document.getElementById("print_name").innerHTML = name;
you were missing one of #(hashtag)
And this code would work
Thanks & Cheers

Validating Input with Javascript

I'm working on a web form with several textboxes and a submit button. When the submit button is clicked, I am supposed to verify that the required fields all have input and that the age field is only numeric. For example, the user can enter 56, but 56 years-old, shouldn't be accepted. If the user enters invalid input or leaves required fields blank, the border around the appropriate textboxes should turn red.
However, as my code is written now all the required fields turn red regardless of input. Any ideas how I can fix this and make the page follow the couple of rules I listed?
Most Recent Code
<html>
<head>
<title>Project 4</title>
<style type="text/css">
body {
background-color: black;
color: blue;
text-align: center;
border: 2px double blue;
}
</style>
</head>
<body>
<h1>Welcome to my Web Form!</h1>
<p>
Please fill out the following information.<br>
Please note that fields marked with an asterisk (*) are required.
</p>
<form name="myForm" id="myForm" onsubmit="return validateForm()">
*Last Name: <br>
<input type="text" id="lastname">
<br>
First Name: <br>
<input type="text" id="firstname">
<br>
*Hobbies (separate each hobby with a comma): <br>
<input type="text" id="hobbies">
<br>
Pets:
<div id="petsContainer">
<input type="text" id="pets">
<input type="button" id="addPet" value="Add Pet">
</div>
<br>
Children:
<div id="childContainer">
<input type="text" id="children">
<input type="button" id="addKid" value="Add Child">
</div>
<br>
*Address: <br>
<input type="text" id="address">
<br>
*Phone Number:<br>
<input type="text" id="phone">
<br>
*Age: <br>
<input type="text" id="age">
<br>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
var validatePhoneOnKeyUpAttached = false;
var validateLNameOnKeyUpAttached = false;
var validateHobbiesOnKeyUpAttached = false;
var validateAddressOnKeyUpAttached = false;
var validateAgeOnKeyUpAttached = false;
function validateForm() {
if(!validatePhoneOnKeyUpAttached) {
document.getElementById("phone").onkeyup = checkPhone;
validatePhoneOnKeyUpAttached = true;
}
else if(!validateLNameOnKeyUpAttached) {
document.getElementById("lastname").onkeyup = checkEmpty;
validateLNameOnKeyUpAttached = true;
}
else if(!validateHobbiesOnKeyUpAttached) {
document.getElementById("hobbies").onkeyup = checkEmpty;
validateHobbiesOnKeyUpAttached = true;
}
else if(!validateAddressOnKeyUpAttached) {
document.getElementById("address").onkeyup = checkEmpty;
validateAddressOnKeyUpAttached = true;
}
else if(!validateAgeOnKeyUpAttached) {
document.getElementById("age").onkeyup = checkEmpty;
document.getElementById("age").onkeyup = checkAge;
validateAgeOnKeyUpAttached = true;
}
return checkEmpty() && checkPhone() && checkAge();
}
function checkPhone() {
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if(phoneNum.length > 6 && phoneNum.length < 11) {
document.getElementById("phone").style.borderColor="transparent";
return true;
}
else if(phoneNum.length < 7 || phoneNum.length > 10) {
document.getElementById("phone").style.borderColor="red";
return false;
}
}
function checkEmpty() {
var lname = document.forms["myForm"]["lastname"].value;
var pNum = document.forms["myForm"]["phone"].value;
var hobs = document.forms["myForm"]["hobbies"].value;
var live = document.forms["myForm"]["address"].value;
var yr = document.forms["myForm"]["age"].value;
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("hobbies").style.borderColor = (hobs == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
document.getElementById("address").style.borderColor = (live == "") ? "red" : "transparent";
document.getElementById("age").style.borderColor = (yr == "") ? "red" : "transparent";
}
function checkAge() {
var age = document.getElementById("age").value;
if(isNan(age)) {
return false;
}
else {
document.getElementById("age").style.borderColor="red";
return true;
}
}
document.getElementById("addPet").onclick=function() {
var div = document.getElementById("petsContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "pats[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
document.getElementById("addKid").onclick=function() {
var div = document.getElementById("childContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "child[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
</script>
</body>
</html>
The problem I'm currently having is that when I click the submit button, all the fields turn red for a split second, but then go back to the regular color and the input is erased. Any thoughts on how to fix this?
By including all of the borderColor="red" statements in a single code block, you're applying that style to all your inputs, even if only one of them failed validation. You need to separate out each statement so that it only applies to the individual field(s) that failed validation:
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
...
Also, I'm using the ternary operator ? : to clean up the code as well. These statements would replace the if-else block you've written.
I am using the following javascript functions in order to validate my form variables. Hope these will helpful for you.
var W3CDOM = (document.getElementsByTagName && document.createElement);
window.onload = function () {
document.forms[0].onsubmit = function () {
return validate()
}
}
function validate() {
validForm = true;
firstError = null;
errorstring = '';
var x = document.forms[0].elements;
for (var i = 0;i < x.length;i++) {
if (!x[i].value) {
validForm = false;
writeError(x[i], 'This field is required');
}
}
// This can be used to validate input type Email values
/* if (x['email'].value.indexOf('#') == -1) {
validForm = false;
writeError(x['email'],'This is not a valid email address');
}
*/
if (!W3CDOM)
alert(errorstring);
if (firstError)
firstError.focus();
return validForm;
}
function writeError(obj, message) {
validForm = false;
//if (obj.hasError) return false;
if (W3CDOM) {
obj.className += ' error';
obj.onchange = removeError;
var sp = document.createElement('span');
sp.className = 'error';
sp.appendChild(document.createTextNode(message));
obj.parentNode.appendChild(sp);
obj.hasError = sp;
} else {
errorstring += obj.name + ': ' + message + '\n';
obj.hasError = true;
}
if (!firstError)
firstError = obj;
return false;
}
function removeError() {
this.className = this.className.substring(0, this.className.lastIndexOf(' '));
this.parentNode.removeChild(this.hasError);
this.hasError = null;
this.onchange = null;
}
You can call the validations right after the form submission as given below.
<form name="loginForm" action="do.login" method="POST" class="form" onsubmit="return validate();">

Adding an event listener using an object’s property

What I want to have is a working button and input form for my code which is a block in an object literal. My form shows fine when I run the code, but doesn’t output a value. Why not?
<input class="number" type="number" placeholder="Enter some number...">
<button>enter</button>
<p id="output"></p>
<script>
var input = document.querySelector("#number");
var output = document.querySelector("#output");
var button = document.querySelector("button");
add.button.addEventListener("click", add.number, false);
button.style.cursor = "pointer";
var add = {
number: function () {
amount = parseInt(input.value);
if (amount == 5) {
output.innerHTML = alert("true");
} else {
output.innerHTML = alert("false");
}
}
};
</script>
You have to define the function before you can pass it to addEventListener otherwise you are just passing undefined.
<input class="number" type="number" placeholder="Enter some number..." id="number">
<button id="button">enter</button>
<p id="output"></p>
var input = document.getElementById("number");
var output = document.getElementById("output");
var add = {
number: function () {
amount = parseInt(input.value, 10);
if (amount === "5") {
alert("true");
output.innerHTML = true;
} else {
alert("false");
output.innerHTML = false;
}
}
};
var button = document.getElementById("button");
button.addEventListener("click", add.number, false);
button.style.cursor = "pointer";
See: http://jsfiddle.net/zw7e7q72/

How to give Input tag attribute type button value at Runtime in Meteor JS

How to give Input tag Attribute type button value at Runtime in Meteor JS as shown below:
newButton = document.createElement('input');
newButton.value = ''; - Here value i need like as i.e , val ="{{btnValue}}"
I'm not familiar with Meteor JS, so please offer any suggestions.
Html Code I need like as below in Runtime JS:
// Manually Creating button
<input type="button" id="no" val ="{{btnValue}}">
My HTML Code :
<head>
<title>TICTACTOE App 1.3</title>
</head>
<body>
{{> uname}}
{{> main}}
{{> games }}
</body>
<template name="uname">
<h1>Welcome to TICTACTOE App</h1>
<p id="pname"><b>User Name :</b> <input type="text" id="uname" ></p>
</template>
<template name="main">
<p id="pno"><b>Layout Number :</b> <input type="text" id="no" ></p>
<div name="main"></div>
</template>
<template name="games">
{{#each game}}
<div>{{turn}} </div>
<div> {{wturn}}</div>
<div>{{bval}}</div>
{{/each}}
</template>
Meteor JS:
Counts = new Meteor.Collection('count');
TurnData= new Meteor.Collection('tdata');
BtnValues= new Meteor.Collection('btnvalues');
var x = "X";
var o = "O";
var Whoseturn = "";
var no;
var newButton;
var count = 0;
var IsWin = false;
var IsTurn = true;
var val = "";
var ButtonValue= "";
var btnval;
if (Meteor.isClient)
{
Template.main.helpers
({
btnValue: function()
{
return BtnValues.findOne();
}
});
Template.main.events
({
'click input' : function ()
{
// template data, if any, is available in 'this'
var name = document.getElementById('uname');
console.log(name.value);
var btnid = event.currentTarget.id;
ButtonValue = btnid;
btnval = document.getElementById(btnid);
console.log(btnid);
if(btnval.value == '' && btnid != "no" )
{
calculateTurn();
console.log(Whoseturn);
btnval.value = Whoseturn;
var myBtnData = BtnValues.findOne();
BtnValues.update( {_id: myBtnData._id},{ $set:{bval : btnval} });
}
}
});
Template.main.events
({
'keydown input#no' : function ()
{
// template data, if any, is available in 'this'
if (event.which == 13)
{
// 13 is the enter key event
console.log("You pressed enter key");
no = document.getElementById('no');
count = 0;
var myTurnData = Counts.findOne();
Counts.update( {_id: myTurnData._id},{ $set:{turn : count } });
if(no.value != '')
{
document.getElementById('pname').style.visibility = 'hidden';
document.getElementById('pno').style.visibility = 'hidden';
UI();
}
}
}
});
}
function UI()
{
console.log("*** UI() ***");
for(var i = 1 ; i <= no.value ; i++)
{
//var body=document.getElementsByTagName('body')[0];
var body = document.getElementsByName('main')[0];
for(var j = 1 ; j <= no.value ; j++)
{
newButton = document.createElement('input');
newButton.type = 'button';
newButton.id = 'btn'+i+j;
newButton.value = '';////Here value i need like as val ="{{btnValue}}
body.appendChild(newButton);
}
var newline = document.createElement('br');
body.appendChild(newline) ;
}
}
function calculateTurn()
{
var myTurnData = Counts.findOne();
count = myTurnData.turn;
console.log("count="+count);
count = count + 1;
console.log("updated count="+count);
Counts.update( {_id: myTurnData._id},{ $set:{turn : count } });
if(count <= 9)
{
var TData = TurnData.findOne();
IsTurn = true;
if(count % 2 == 0)
{
Whoseturn = o ;
TurnData.update( {_id: TData._id},{ $set:{wturn : Whoseturn } });
}
else
{
Whoseturn = x ;
TurnData.update( {_id: TData._id},{ $set:{wturn : Whoseturn } });
}
}
else
{
IsTurn = false;
console.log(" >= 9");
}
}
if (Meteor.isServer)
{
Meteor.startup(function ()
{
// code to run on server at startup
Counts.insert({turn : count});
TurnData.insert({wturn : Whoseturn});
BtnValues.insert({bval : val});
});
}

Categories