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.
Related
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';
}
}
the correct or wrong answer outputs and quickly disappears. How do I get the answer to remain on the screen. I want to keep the html and js files separate. What I want to do later is add other phrases to the program.
INDEX.HTML
<head> </head>
<body>
<form name="myForm">
<div id ="phrase"></div>
<input type = "text" id = "textinput">
<button id="myBtn">Click here</button>
<div id ="feedback"></div>
</form>
<script src = "phraseScrambler.js"></script>
</body>
</html>
PHRASESCRAMBLER.JS
var words = ['how', 'are', 'you', 'today?'];
var correctInput = "how are you today";
var userInput = 'how are you today?';
var newWords = words.slice(0);
shuffle(newWords);
question();
function question() {
var el = document.getElementById('phrase');
el.textContent = newWords.join(' ');
document.getElementById("myBtn").onclick = checkAnswer;}
function checkAnswer() {
var elMsg = document.getElementById('feedback');
if (document.myForm.textinput.value == correctInput) {
elMsg.textContent= "correct";}
else {
elMsg.textContent= "wrong answer";}}
function shuffle(newWords) {
var counter = newWords.length, temp, index;
while (counter > 0) {
index = Math.floor(Math.random() * counter);
counter--;
temp = newWords[counter];
newWords[counter] = newWords[index];
newWords[index] = temp;}
return newWords;}
First of all don't bind click event if you want to handle form submission, forms have dedicated event called onsubmit. When form is submitted default browser behavior is to navigate to form action (in your case reload the page). You need to prevent this by returning false from the onsubmit handler.
Corrected HTML will be (I gave an id to the form):
<form name="myForm" id="myForm"> ... </form>
And then event handling will look like (note return false; in checkAnswer function):
var words = ['how', 'are', 'you', 'today?'];
var correctInput = "how are you today";
var userInput = 'how are you today?';
var newWords = words.slice(0);
shuffle(newWords);
question();
function question() {
var el = document.getElementById('phrase');
el.textContent = newWords.join(' ');
document.getElementById("myForm").onsubmit = checkAnswer;
}
function checkAnswer() {
var elMsg = document.getElementById('feedback');
if (document.myForm.textinput.value == correctInput) {
elMsg.textContent = "correct";
} else {
elMsg.textContent = "wrong answer";
}
return false;
}
function shuffle(newWords) {
var counter = newWords.length,
temp, index;
while (counter > 0) {
index = Math.floor(Math.random() * counter);
counter--;
temp = newWords[counter];
newWords[counter] = newWords[index];
newWords[index] = temp;
}
return newWords;
}
<form name="myForm" id="myForm">
<div id ="phrase"></div>
<input type = "text" id = "textinput" />
<button>Click here</button>
<div id ="feedback"></div>
</form>
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();">
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/
please be nice. I'm trying to create a page which sets limit and cut the excess (from the specified limit). Example: Limit is 3. then, I'll input abc if I input d it must say that its limit is reached and the abc will remain. My problem is that it just delete my previous input and make new inputs. Hoping for your great cooperation. Thanks.
<html>
<script type="text/javascript">
function disable_btn_limit(btn_name)
{
/* this function is used to disable and enable buttons and textbox*/
if(btn_name == "btn_limit")
{
document.getElementById("btn_limit").disabled = true;
document.getElementById("ctr_limit_txt").disabled = true;
document.getElementById("btn_edit_limit").disabled = false;
}
if(btn_name == "btn_edit_limit")
{
document.getElementById("btn_limit").disabled = false;
document.getElementById("ctr_limit_txt").disabled = false;
document.getElementById("btn_edit_limit").disabled = true;
}
}
function check_content(txtarea_content)
{
/*This function is used to check the content*/
// initialize an array
var txtArr = new Array();
//array assignment
//.split(delimiter) function of JS is used to separate
//values according to groups; delimiter can be ;,| and etc
txtArr = txtarea_content.split("");
var newcontent = "";
var momo = new Array();
var trimmedcontent = "";
var re = 0;
var etoits;
var etoits2;
//for..in is a looping statement for Arrays in JS. This is similar to foreach in C#
//Syntax: for(index in arr_containter) {}
for(ind_val in txtArr)
{
var bool_check = check_if_Number(txtArr[ind_val])
if(bool_check == true)
{
//DO NOTHING
}
else
{
//trim_content(newcontent);
newcontent += txtArr[ind_val];
momo[ind_val] = txtArr[ind_val];
}
}
var isapa = new Array();
var s;
re = trim_content(newcontent);
for(var x = 0; x < re - 1; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
}
function trim_content(ContentVal)
{
//This function is used to determine length of content
//parseInt(value) is used to change String values to Integer data types.
//Please note that all value coming from diplay are all in String data Type
var limit_char =parseInt(document.getElementById("ctr_limit_txt").value);
var eto;
if(ContentVal.length > (limit_char-1))
{
alert("Length is greater than the value specified above: " +limit_char);
eto = limit_char ;
etoits = document.getElementById("txtarea_content").value;
//document.getElementById("txtarea_content").value = "etoits";
return eto;
//for(var me = 0; me < limit_char; me++)
//{document.getElementById("txtarea_content").value = "";}
}
return 0;
}
function check_if_Number(ContentVal)
{
//This function is used to check if a value is a number or not
//isNaN, case sensitive, JS function used to determine if the values are
//numbers or not. TRUE = not a number, FALSE = number
if(isNaN(ContentVal))
{
return false;
}
else
{ alert("Input characters only!");
return true;
}
}
</script>
<table>
<tr>
<td>
<input type="text" name="ctr_limit_txt" id="ctr_limit_txt"/>
</td>
<td>
<input type="button" name="btn_limit" id="btn_limit" value="Set Limit" onClick="javascript:disable_btn_limit('btn_limit');"/>
</td>
<td>
<input type="button" name="btn_edit_limit" id="btn_edit_limit" value="Edit Limit" disabled="true" onClick="javascript:disable_btn_limit('btn_edit_limit');"/>
</td>
</tr>
<tr>
<td colspan="2">
<textarea name="txtarea_content" id="txtarea_content" onKeyPress="javascript:check_content(this.value);"></textarea>
<br>
*Please note that you cannot include <br>numbers inside the text area
</td>
</tr>
</html>
Try this. If the condition is satisfied return true, otherwise return false.
<html>
<head>
<script type="text/javascript">
function check_content(){
var text = document.getElementById("txtarea_content").value;
if(text.length >= 3){
alert('Length should not be greater than 3');
return false;
} else {
return true;
}
}
</script>
</head>
<body>
<div>
<textarea name="txtarea_content" id="txtarea_content" onkeypress=" return check_content();"></textarea>
</div>
</body>
</html>
Instead of removing the extra character from the text area, you can prevent the character from being written in the first place
function check_content(event) { //PARAMETER is the event NOT the content
txtarea_content = document.getElementById("txtarea_content").value; //Get the content
[...]
re = trim_content(newcontent);
if (re > 0) {
event.preventDefault(); // in case the content exceeds the limit, prevent defaultaction ie write the extra character
}
/*for (var x = 0; x < re - 1; x++) {
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}*/
}
And in the HTML (parameter is the event):
<textarea ... onKeyPress="javascript:check_content(event);"></textarea>
Try replacing with this:
for(var x = 0; x < re - 6; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
Any reason why the maxlength attribute on a text input wouldn't work for so few characters? In your case, you would have:
<input type="text" maxlength="3" />
or if HTML5, you could still use a textarea:
<textarea maxlength="3"> ...
And then just have a label that indicates a three-character limit on any input.