My function or button isn't working - javascript

Any help is appreciated and my code is posted below.
I've read my course book, followed the instructions of my professor, gone on youtube, read forums and still don't know why my button is not running my function when I click it. Please help.
HTML:
<!doctype html>
<head>
<h1>Exercise 3-1</h1>
<script src ="X_3_1.js"></script>
</head>
<body>
<p>Enter First Name:
<input type="text" id="firstName">
<br>
Do you have children?:
<input type="text" id="children">
<br>
If so, how old is your oldest child?:
<input type="text" id="oldestChild">
<br>
<input type="button" onclick="processInfo()" value="Submit Information">
<br>
<span id="mymsg">*</span>
</p>
</body>
</html>
JS:
function processInfo()
{
var firstName = document.getElementById("firstName").value;
var children = document.getElementById("children").value;
var oldestChild = document.getElementById("oldestChild").value;
var childrenLower = children.toLowerCase();
var today = new Date ();
if(childrenLower == "yes" || childrenLower == "y")
{
if(isNaN(oldestChild)){
mymsg.firstChild.nodeValue = oldestChild + " is not a number";
} else if(oldestChild <= 19){
mymsg.firstChild.nodeValue = "You still have kids at home";
} else if(oldestChild >= 19){
mymsg.firstChild.nodeValue = "Hopefully they have moved out of the
house";
}
} else if(childrenLower != "yes" || childrenLower != "y") {
mymsg.firstChild.nodeValue = "It must be peacefule at home, " +
firstName + "on this date of " today;
}
}

I figured it out. I was missing a + sign before the variable today on the last line. Thanks anyway.

Related

If statement doesn't work in JavaScript - HTML

I'm pretty new to HTML, and I'm trying to make a simple login system. I'm using Sublime Text 3 and "If" statements in JavaScript don't work. When I type 'if' in script, it goes purple, not JavaScript blue. Am I bad or is Sublime not working at all?
Code:
<html>
<body>
Kullanıcı adı: <input type="text" id="kadi">
<br>
Şifre:<input type="text" id="sifre">
<br>
<button type="button" onclick="fun()">Giriş Yap</button>
<p id="p"></p>
<script type="text/javascript">
function fun(){
var gkadi = document.getElementById().value;
var gsif = document.getElementById().value;
var dkadi = "ali";
var dsif = "aa123"
if(gkadi==dkadi){
if(gsif==dsif){
document.getElementById("p").innerHTML = "Giriş başarılı!";
} else {
document.getElementById("p").innerHTML = "Şifre yanlış";
}
} else {
document.getElementById("p").innerHTML = "Kullanıcı adı yanlış.";
}
}
</script>
</body>
</html>
The syntax coloring can be misleading. It's not your if statement that is having problems. It's that getElementById() expects one argument which should be the id of the element that you are trying to get. With that change, your code works fine.
function fun() {
var gkadi = document.getElementById("kadi").value;
var gsif = document.getElementById("sifre").value;
var dkadi = "ali";
var dsif = "aa123"
if (gkadi == dkadi) {
if (gsif == dsif) {
document.getElementById("p").innerHTML = "Giriş başarılı!";
} else {
document.getElementById("p").innerHTML = "Şifre yanlış";
}
} else {
document.getElementById("p").innerHTML = "Kullanıcı adı yanlış.";
}
}
Kullanıcı adı: <input type="text" id="kadi">
<br> Şifre:
<input type="text" id="sifre">
<br>
<button type="button" onclick="fun()">Giriş Yap</button>
<p id="p"></p>

How to fix the logic problem in my loop for my basic logon screen

I get the code to tell me when someone types in a bad userid or password. And I can get it to let people in when the get they type in the first userid and password
user1 and pass1
But, if they try user2 and pass2 it says it is a wrong password. I know it is a logic error on my part with the loop, but, cant figure it out for the life of me! Please help me understand if you guys can!
Thank you
<!DOCTYPE html>
<html lang="en">
<head>
<title>Assignment 1</title>
<link rel="stylesheet" type="text/css" href="css/login.css">
</head>
<body>
<script>
document.body.style.backgroundColor = "grey";
var valid = false;
function validate() {
var useArray = ["user1", "user2", "user3"];
var passArray = ["pass1", "pass2", "pass3"];
var x = document.login.userId.value;
var y = document.login.passWord.value;
for(var i = 0; i < useArray.length; i++) {
if (x == useArray[i] && y == passArray[i]) {
document.write("You have successfully logged on to your
class!");
return false;
} else if (i = useArray.length - 1) {
document.write("Error: User Id is not valid, please click the
link below again \n \n");
var l =(" link back");
var back = l.link("practice.html");
document.write(back);
return false;
}
}
}
</script>
<div class="container">
<h1>Logon</h1>
<form name="login">
<label for="useId">Userid: </label>
<input type="text" name="userId" required>
<br><br>
<label for="passWord">Password: </label>
<input type="password" name="passWord" required>
<br><br>
<input type="button" class="submit" value="Log In" name="submit"
onclick="validate(this.form)">
</form>
</div>
<br><br>
</body>
</html>
I need it to accept the other parts of the Array too. When someone puts in usee2 and pass2 for example
Thank you
You're having trouble over here else if (i = useArray.length - 1)
useArray.length is going to be 3 for all loops so userArray.length - 1 will always eval to 2, you're setting i = 2 inside the if
in JS the assignment operator also returns the value assigned so you're basically writing
else if( 2 ) which will always evaluate to true

Javascript and DOM - Date and Time

I am creating a resume site and I'm trying to create a function that will load when the page loads that displays a greeting (as a heading) depending on the time of day. Here is what I have so far (you can ignore the salary calculator part):
<body onload = "onLoad()">
<div id="fulldiv">
<p> Enter the following information to find out if the potential salary is too little, almost enough, or a good salary.</p>
<p>Hourly Wage:
<input type="text" name="wage" id="txt_wage" value ="0.00"/></p>
<p>Hours Per Week:
<input type="text" name="hours" id="txt_hours" value= "0.0"/> <br/><br/>
<button value="calculate" onclick="calcSalary(); validateForm(); validateFormH()">Calculate</button></p>
<p id="results"></p>
<p id="resultstext"></p>
<script src="salaryExternal.js" type="text/javascript"></script>
<script type="text/javascript">
function onLoad() {
var d = new Date();
var z = d.getHours();
var greeting;
if (z < 12) {
greeting = "Enjoy the rest of your morning!"
} else if (z < 17) {
greeting = "Enjoy the afternoon!"
} else {
greeting = "Have a good evening!"
}
}
var firstVariable = document.createElement("h1");
var secondVariable = document.createTextNode(d);
firstVariable.appendChild(secondVariable);
document.getElementById("fulldiv").appendChild(firstVariable);
</script>
</div>
Nothing is showing up when I load the page. I'm not sure where to go from here. Any help would be greatly appreciated.
You need to set greeting variable as text node value and move HTML element creation code inside onLoad funtion as follows -
<body onload="onLoad()">
<div id="fulldiv">
<p> Enter the following information to find out if the potential salary is too little, almost enough, or a good salary.</p>
<p>Hourly Wage:
<input type="text" name="wage" id="txt_wage" value="0.00" />
</p>
<p>Hours Per Week:
<input type="text" name="hours" id="txt_hours" value="0.0" />
<br/>
<br/>
<button value="calculate" onclick="calcSalary(); validateForm(); validateFormH()">Calculate</button>
</p>
<p id="results"></p>
<p id="resultstext"></p>
</div>
<script src="salaryExternal.js" type="text/javascript"></script>
<script type="text/javascript">
function onLoad() {
var d = new Date();
var z = d.getHours();
var greeting;
if (z < 12) {
greeting = "Enjoy the rest of your morning!"
} else if (z < 17) {
greeting = "Enjoy the afternoon!"
} else {
greeting = "Have a good evening!"
}
var firstVariable = document.createElement("h1");
var secondVariable = document.createTextNode(greeting);
firstVariable.appendChild(secondVariable);
document.getElementById("fulldiv").appendChild(firstVariable);
}
</script>
The last few lines of your code are defined outside the onLoad function:
function onLoad() {
...
}
var firstVariable = document.createElement("h1");
var secondVariable = document.createTextNode(d);
firstVariable.appendChild(secondVariable);
document.getElementById("fulldiv").appendChild(firstVariable);
which is why it does not work as expected.

Checking if integer JavaScript forms

I have begun learning javascript and I cannot get the security code part of my form (and I have yet to fix the other things such as card number) to bring up an alert if they have not entered 3 integers, I can get it to alert if the person doesnt enter 3 ints/strings/symbols etc... but > or < 3. However I cannot get it to alert the user if the things they pass are not integers. Thank you!.
edit: so the issue im trying to solve is how to run my is_int function on the theForm.cvs.value im sorry if im unclear its all a bit messy.
<script type="text/JavaScript">
function is_int(value){
if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
return true;
} else {
return false;
}
};
function verification(theForm) {
content = "";
var cardLen = (theForm.cardLength.value).length;
var securitycode = new is_int(theForm.cvs.value);
if (cardLen !== 16) {
content += "Please make sure you've entered 16 digits.";
}
if ((theForm.userName.value).length === 0) {
content += "Please make sure you've entered the correct name.";
}
if ((theForm.month.value) < 1 || theForm.month.value > 12 || theForm.month.value === "" || theForm.month.value === "MM") {
content += "Please make sure the you've entered the correct month.";
}
if ((theForm.year.value) < 2016 || ((theForm.year.value) === "" )) {
content += "Please make sure you've entered the correct expiry year.";
}
if ( !securitycode || ( (theForm.cvs.value).length !== 3) ) {
content += "Please make sure you've entered the correct security code.";
}
if (!content == "") {
alert (content); return false;
}
};
</script>
</head>
<body>
<br>
<br>
<br>
<center><h1>Checkout:</h1></center>
<div style="position:absolute; left:600px; top:200px;">
<form name="myForm" class="theForm" onSubmit="return verification(this)" >
Card Number: Expiration:
<br>
<input type="text" name="cardLength"> <input type="text" name="month" style="width:30px" value="MM"> - <input type="text" name="year" style="width:30px" value="YY">
<br>
Name: Security Code:
<br>
<input type="text" name="userName"> <input type="text" name="cvs" style="width:30px">
<br>
<br>
<input type="submit" value="Submit">
</form>
</div>
You don't want to create a new is_int. New creates an instance of an object and calls its constructor, but you just need to get a return value from a function.
if ( !is_int(theForm.cvs.value) || theForm.cvs.value.length !== 3 ) {
content += "Please make sure you've entered the correct security code.";
}

Simple Age Verification in javascript

I'm a total Js noob and i'm trying to make a simple script to take values from two input tags and based on their value change a p tag. I'm probably just not using proper syntax but I can't find an answer online to how to do this.
The script is supposed to be like age verification for an r-rated movie. The first input is age and the second is whether or not the customer has an adult with them for if they are underage.
<pre>
<!DOCTYPE html>
<html>
<input type="text" id="age" value="your age">
<input type="text" id="adult" value="(y or n)">
<input type="button" onclick="checkAge()" value="submit">
<p id="answer"></p>
<script>
var age = document.getElementById("age").innerHTML;
var adult = document.getElementById("adult").innerHTML;
var result = document.getElementById("answer").innerHTML;
var oldEnough = false;
function checkAge(){
if(age.value >= 18){
oldEnough = true;
}
else{
oldEnough = false;
}
if(oldEnough == false){
if(adult.value == "y"){
result = "You are not old enough, but have an adult with you.";
}
else{
result = "You are not old enough and are unaccompanied."
}
}
else{
result = "You are old enough."
}
}
</script>
</html>
</pre>
Don't call .innerHTML on the input elements. Just set the variables to point to the elements.
When assigning the result, you need to use result.innerHTML at the time of the assignment. Assigning .innerHTML to the variable just copies the current contents of the element as a string, it doesn't make result a reference to the innerHTML property.
You should call parseInt on age, because .value is a string.
function checkAge() {
var age = document.getElementById("age");
var adult = document.getElementById("adult");
var oldEnough = false;
var result = document.getElementById("answer")
if (parseInt(age.value, 10) >= 18) {
oldEnough = true;
} else {
oldEnough = false;
}
if (oldEnough == false) {
if (adult.value == "y") {
result.innerHTML = "You are not old enough, but have an adult with you.";
} else {
result.innerHTML = "You are not old enough and are unaccompanied."
}
} else {
result.innerHTML = "You are old enough."
}
}
<input type="text" id="age" placeholder="your age">
<input type="text" id="adult" placeholder="(y or n)">
<input type="button" onclick="checkAge()" value="submit">
<p id="answer"></p>
The input elements can be more easily accessed if they are put in a form, and the logic can be simpler. Also, make sure you use appropriate elements and attributes, e.g. don't use value as a kind of placeholder, it should be a suitable default value (if there is one).
And don't use placeholders instead of labels, they should only be used as a hint for the kind of content required, they don't replace labels.
function checkAge(button) {
var form = button.form;
var result = document.getElementById("answer");
result.innerHTML = form.age.value >= 18? 'You are old enough.' :
form.adult.checked? 'You are not old enough, but have an adult with you.' :
'You are not old enough and are unaccompanied.';
}
<form>
<label>Age: <input type="text" name="age"></label>
<label>Adult: <input type="checkbox" name="adult"></label>
<input type="button" onclick="checkAge(this)" value="Check age">
<p id="answer"></p>
</form>

Categories