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>
Related
I have a problem. When I want to log in, I get "ERROR" every time, although I enter good login details.
I am completely beginner in JavaScript and HTML, so please bear with me :-)
There is code:
function login() {
var login = document.getElementById("login");
var password = document.getElementById("haslo");
var lGOOD = "adi282123";
var pGOOD = "qaz123qaz123";
var status;
if (login === lGOOD && password === pGOOD) {
greeting = "OK";
} else {
greeting = "ERROR";
}
document.getElementById("demo").innerHTML = greeting;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<p>Zaloguj się</p>
<br id=login><input type="text" name="login"><br>
<br id=haslo><input type="text" name="password">
<button onclick="login()">Zaloguj się !!!</button>
<p id="demo"></p>
<script>
</script>
</body>
</html>
There are two issues in your code:
You have set id to the wrong elements. You have to set id's to input elements.
You have to take the value from the input element
function login() {
var login = document.getElementById("login").value;
var password = document.getElementById("haslo").value;
var lGOOD = "adi282123";
var pGOOD = "qaz123qaz123";
var status;
if (login === lGOOD && password === pGOOD)
{
greeting = "OK";
}
else
{
greeting = "ERROR";
}
document.getElementById("demo").innerHTML = greeting;
}
<p>Zaloguj się</p>
<br><input id="login" type="text" name="login"><br>
<br><input id="haslo" type="text" name="password">
<button onclick="login()">Zaloguj się !!!</button>
<p id="demo"></p>
I want to create a randomly generated number, ask the user to enter a number, then compare the two and then show a popup telling whether or not they match. This is my code
function myFunction() {
var num=document.getElementById("demo").innerHTML = Math.floor(1000 + Math.random() * 9000);
}
function myFunction1() {
var secondInput = document.getElementById("demo1").value;
if( num === secondInput)
{
window.alert("Same");
}
else
{
window.alert("Don't do that again cvv");
}
<button onclick="myFunction()">press the button to see the code</button>
<p id="demo"></p>
code: <input type="text" name="code" required/><br/><br/>
<button onclick="myFunction1()">Compare</button>
<p id="demo1"></p>
This code works. Please know that there were a couple of improvements:
You referenced to myFunction() before the javascript is loaded.
You need to keep the var num in global scope if you want to reference it in other places, without passing them as an argument.
When comparing values, make sure to select the right input field and to convert the value string to a Number.
var num;
function myFunction() {
num=document.getElementById("demo").innerHTML = Math.floor(1000 + Math.random() * 9000);
}
document.getElementById("button1").addEventListener('click', myFunction)
document.getElementById("button2").addEventListener('click', myFunction1)
function myFunction1() {
var secondInput = document.getElementById("demo1").value;
if( num === +secondInput) {
window.alert("Same");
}
else {
window.alert("Don't do that again cvv");
}
}
<button id="button1" >press the button to see the code</button>
<p id="demo"></p>
code: <input id="demo1" type="text" name="code" required/><br/><br/>
<button id="button2">Compare</button>
<p></p>
First you have to define num in the global scope to be accessable by the two functions and you have to make the first function just show the number without generating a new number every time.
var num;
function show() {
document.getElementById("demo").innerHTML = num;
}
function randomizeAndCompare() {
num = Math.floor(1000 + Math.random() * 9000);
var secondInput = document.getElementById("demo1").value;
if( num === secondInput){
window.alert("Same");
}
else{
window.alert("Don't do that again cvv");
}
}
<button onclick="show()">press the button to see the code</button>
<p id="demo"></p>
code: <input type="text" name="code" required/><br/><br/>
<button onclick="randomizeAndCompare()">Compare</button>
<p id="demo1"></p>
There are a couple of tings here.
First, myFunction1() isn't closed. You should also rename it to something more meaningful, like "compareValue()". That way it is easier to read the code.
You also aren't making a comparison of the two numbers in your compareValue()-function. Your 'num' variable isn't defined. You are also trying to extract the user input value from the button.
See my suggestion for changes:
function generateRandom() {
document.getElementById("demo").innerHTML = Math.floor(1000 +
Math.random() * 9000);
}
function compareValues() {
var num = document.getElementById("demo").innerHTML;
var input = document.getElementById("number").value;
if( num === input)
{
window.alert("Same");
}
else
{
window.alert("Don't do that again cvv");
}
}
HTML:
<button onclick="generateRandom()">press the button to see the code</button>
<p id="demo"></p>
code: <input id="number" type="text" name="code" required/><br/><br/>
<button onclick="compareValues()">Compare</button>
<p id="demo1"></p>
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.
My javascript code, thanks in advance (let me know if you need the html too but its basically the tags, it's a game where the players just click until it reaches a certain number, and whoever reaches first wins. I'm trying to stop the other player from clicking if the game has already been won:
var player1Score=0;
var player2Score=0;
function p1Function(){
if(player1Score==document.querySelector("input").value)
return;
++player1Score;
document.querySelector("#pOneScore").innerHTML=player1Score.toString();
if(player1Score==document.querySelector("input").value)
document.querySelector("#pOneScore").style.color="green";
}
function p2Function(){
if(player2Score==document.querySelector("input").value)
{
document.querySelector(".playerOne").removeEventListener("click",
p1Function);
return;
}
player2Score++;
document.querySelector("#pTwoScore").innerHTML=player2Score.toString();
if(player2Score==document.querySelector("input").value)
document.querySelector("#pTwoScore").style.color="green";
}
function resetFunction(){
document.querySelector("input").value=5;
document.querySelector("#pOneScore").style.color="black";
document.querySelector("#pTwoScore").style.color="black";
player1Score=0;
player2Score=0;
document.querySelector("#pOneScore").innerHTML=player1Score.toString();
document.querySelector("#pTwoScore").innerHTML=player2Score.toString();
}
document.querySelector(".playerOne").addEventListener("click", p1Function);
document.querySelector(".playerTwo").addEventListener("click", p2Function);
document.querySelector(".reset").addEventListener("click", resetFunction);
Here is the HTML code as requested:
<body>
<strong><span id="pOneScore">0</span> to <span id="pTwoScore">0</span>
</strong>
<br>
<br>
<p>Playing To:</p> <span id="playing_to"></span>
<input type="text" name="score" value="5"></input>
<button class="playerOne">Player One</button>
<button class="playerTwo">Player Two</button>
<button class="reset">Reset</button>
<script src="scorekeeper_js"></script>
</body>
You didn't remove listener in one of your onclick functions.
function p1Function() {
var maxScore = document.querySelector("input").value;
player1Score++;
if (player1Score == maxScore) {
document.querySelector("#pOneScore").style.color = "green";
document.querySelector(".playerTwo").removeEventListener("click",
p2Function);
document.querySelector("#pOneScore").innerHTML = player1Score.toString();
} else if (player1Score < maxScore) {
document.querySelector("#pOneScore").style.color = "black";
document.querySelector("#pOneScore").innerHTML = player1Score.toString();
}
}
function p2Function() {
var maxScore = document.querySelector("input").value;
player2Score++;
if (player2Score == maxScore) {
document.querySelector("#pTwoScore").style.color = "green";
document.querySelector(".playerOne").removeEventListener("click",
p1Function);
document.querySelector("#pTwoScore").innerHTML = player2Score.toString();
} else if (player2Score < maxScore) {
document.querySelector("#pTwoScore").style.color = "black";
document.querySelector("#pTwoScore").innerHTML = player2Score.toString();
}
}
You also have to add listeners back in reset():
function resetFunction() {
...
document.querySelector(".playerOne").addEventListener("click", p1Function);
document.querySelector(".playerTwo").addEventListener("click", p2Function);
}
Here is working jsfiddle code:
https://jsfiddle.net/1we2ydza/1/
Check it now
var player1Score=0;
var player2Score=0;
function p1Function(){
if(player1Score==parseInt(document.querySelector("input").value)){
document.querySelector(".playerTwo").removeEventListener("click",
p2Function);
return;
}
++player1Score;
document.querySelector("#pOneScore").innerHTML=player1Score.toString();
if(player1Score==document.querySelector("input").value)
document.querySelector("#pOneScore").style.color="green";
}
function p2Function(){
if(player2Score==parseInt(document.querySelector("input").value))
{
document.querySelector(".playerOne").removeEventListener("click",
p1Function);
return;
}
player2Score++;
document.querySelector("#pTwoScore").innerHTML=player2Score.toString();
if(player2Score==document.querySelector("input").value)
document.querySelector("#pTwoScore").style.color="green";
}
function resetFunction(){
document.querySelector("input").value=5;
document.querySelector("#pOneScore").style.color="black";
document.querySelector("#pTwoScore").style.color="black";
player1Score=0;
player2Score=0;
document.querySelector(".playerOne").addEventListener("click", p1Function);
document.querySelector(".playerTwo").addEventListener("click", p2Function);
document.querySelector("#pOneScore").innerHTML=player1Score.toString();
document.querySelector("#pTwoScore").innerHTML=player2Score.toString();
}
document.querySelector(".playerOne").addEventListener("click", p1Function);
document.querySelector(".playerTwo").addEventListener("click", p2Function);
document.querySelector(".reset").addEventListener("click", resetFunction);
<body>
<strong><span id="pOneScore">0</span> to <span id="pTwoScore">0</span>
</strong>
<br>
<br>
<p>Playing To:</p> <span id="playing_to"></span>
<input type="text" name="score" value="5" />
<button class="playerOne">Player One</button>
<button class="playerTwo">Player Two</button>
<button class="reset">Reset</button>
<script src="scorekeeper_js"></script>
</body>
Once the 1st person clicks the 5, times then in the person one handler, the click handler for person two was not removed. Hence the person two was able to click. I think you hand missed to remove the click in 'p1Function()'. Adding the below lines in 'p1Function()' would solve your problem:
if(player1Score==document.querySelector("input").value)
{
document.querySelector(".playerTwo").removeEventListener("click",
p2Function);
return;
}
Im getting a error in the Web Inspector as shown below:
TypeError: 'null' is not an object (evaluating 'myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
return false;
}')
Here is my Code (HTML):
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>
<script src="js/script.js" type="text/javascript"></script>
<form>
<input type="text" id="myTextfield" placeholder="Type your name" />
<input type="submit" id="myButton" value="Go" />
</form>
Here is the JS:
var myButton = document.getElementById("myButton");
var myTextfield = document.getElementById("myTextfield");
function greetUser(userName) {
var greeting = "Hello " + userName + "!";
document.getElementsByTagName ("h2")[0].innerHTML = greeting;
}
myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
return false;
}
Any Idea why I am getting the error?
Put the code so it executes after the elements are defined, either with a DOM ready callback or place the source under the elements in the HTML.
document.getElementById() returns null if the element couldn't be found. Property assignment can only occur on objects. null is not an object (contrary to what typeof says).
Any JS code which executes and deals with DOM elements should execute after the DOM elements have been created. JS code is interpreted from top to down as layed out in the HTML.
So, if there is a tag before the DOM elements, the JS code within script tag will execute as the browser parses the HTML page.
So, in your case, you can put your DOM interacting code inside a function so that only function is defined but not executed.
Then you can add an event listener for document load to execute the function.
That will give you something like:
<script>
function init() {
var myButton = document.getElementById("myButton");
var myTextfield = document.getElementById("myTextfield");
myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
}
}
function greetUser(userName) {
var greeting = "Hello " + userName + "!";
document.getElementsByTagName ("h2")[0].innerHTML = greeting;
}
document.addEventListener('readystatechange', function() {
if (document.readyState === "complete") {
init();
}
});
</script>
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>
<form>
<input type="text" id="myTextfield" placeholder="Type your name" />
<input type="button" id="myButton" value="Go" />
</form>
Fiddle at - http://jsfiddle.net/poonia/qQMEg/4/
Try loading your javascript after.
Try this:
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>
<form>
<input type="text" id="myTextfield" placeholder="Type your name" />
<input type="submit" id="myButton" value="Go" />
</form>
<script src="js/script.js" type="text/javascript"></script>
I think the error because the elements are undefined ,so you need to add window.onload event which this event will defined your elements when the window is loaded.
window.addEventListener('load',Loaded,false);
function Loaded(){
var myButton = document.getElementById("myButton");
var myTextfield = document.getElementById("myTextfield");
function greetUser(userName) {
var greeting = "Hello " + userName + "!";
document.getElementsByTagName ("h2")[0].innerHTML = greeting;
}
myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
return false;
}
}
I agree with alex about making sure the DOM is loaded. I also think that the submit button will trigger a refresh.
This is what I would do
<html>
<head>
<title>webpage</title>
</head>
<script type="text/javascript">
var myButton;
var myTextfield;
function setup() {
myButton = document.getElementById("myButton");
myTextfield = document.getElementById("myTextfield");
myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
return false;
}
}
function greetUser(userName) {
var greeting = "Hello " + userName + "!";
document.getElementsByTagName("h2")[0].innerHTML = greeting;
}
</script>
<body onload="setup()">
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>
<form>
<input type="text" id="myTextfield" placeholder="Type your name" />
<input type="button" id="myButton" value="Go" />
</form>
</body>
</html>
have fun!