javascript- resetting a variable - javascript

I am trying to make a basic program to run on a html page. It gives you an answer after clicking a button and inputing something and looks like:
<button type="button" onclick="whatsong()">Click to enter a song</button>
<p id="result"></p>
<script>
function whatsong() {
var song = prompt("please enter a song");
if (song = "example") {
document.getElementById("result").innerHTML = "yes";
}
if (song = "example2") {
document.getElementById("result").innerHTML = "no";
}
</script>
I want the variable song to reset so that the user could enter a song that prints no onto the webpage, then press the button again and enter a song that would yield a yes, without it still displaying no', like it does at the moment, and instead printing yes.
UPDATE: http://istyjorapping.atwebpages.com/ is the actual webpage, and it has multiple options per if (e.g.
if (song == "heavydirtysoul", "ode to sleep", "fake you out", "forest")
{ document.getElementById("result").innerHTML = "yes";
}), and any suggestions i have tried so far have made it give some strange results that the debugger i normally use can't work out.

You need to use ==(Equality) or ===(Identity) operator instead of =(assignment)operator
function whatsong() {
var song = prompt("please enter a song");
if (song == "example"){
document.getElementById("result").innerHTML = "yes";
}
if (song == "example2"){
document.getElementById("result").innerHTML = "no";
}
}
A good read Which equals operator (== vs ===) should be used in JavaScript comparisons?
<button type="button" onclick="whatsong()">Click to enter a song</button>
<p id="result"></p>
<script>
function whatsong() {
var song = prompt("please enter a song");
if (song == "example") {
document.getElementById("result").innerHTML = "yes";
}
if (song == "example2") {
document.getElementById("result").innerHTML = "no";
}
}
</script>

So as i have understood, on the click of a button you want to take a user input and based on the user input you want to display a particular text.
Below is the sample code for that
HTML
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click Me</button>
<p id="result"></p>
JS will be
function myFunction() {
var song = prompt("please enter a song");
if(song==='example'){
document.getElementById("result").innerHTML = "yes";
}
if(song==='example2'){
document.getElementById("result").innerHTML = "no";
}
}
I HOPE THIS HELPED. LET me know if you liked the solution. There can be many multiple ways too.

Related

Asking for user's input inside a while loop in javaScript

I'm creating a number guessing game in JavaScript. I'm using the input.value property to get user input. Now I have a while loop which should execute until the number entered by user is equal to the actual number. But I'm unable to get out of loop and ask for user input again as the while loop always evaluates to true. How can I ask for user's input again. Please suggest anything else rather than using prompt.
var correctNumber = 16
function answer() {
while (inputNumber !== correctNumber) {
var inputNumber = Number(inputValue.value)
inputNumber = Number(inputValue.value)
}
}
<html>
<body>
<label for="answer">Your guess:</label>
<input type="text" id="answer" name="answer" />
<button onclick="guessAnswer">Guess Answer</button>
<p id="feedback"></p>
<script>
const correctNumber = 16;
const feedback = document.getElementById('feedback');
function guessAnswer() {
const answer = document.getElementById('answer');
if(answer == correctNumber) {
feedback.innerHTML = 'Correct';
} else {
feedback.innerHTML = 'Incorrect';
}
}
</script>
<body>
</html>

How to display confirm box on website in php

i want to display an confirm box with two button yes and no, when user press yes than index page will be displayed and when user press no this redirect to another page. this confirm msgbox display only once when first time website open not on every reloading of page. Thanks
you can try this code
<script>
var confirm = confirm("sample message?");
if(confirm) {
// index page
window.location.url = ""; // your url index page
} else {
// other page
window.location.url = ""; // your url other page
}
</script>
You have to do all stuff in javascript.
Javascript Function you can use.
Also you need to set cookie at browser and check if cookie is set.
function myFunction() {
var x;
if (confirm("Press a button!") == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = x;
}
Hope this helps.
function myFunction() {
var txt;
var r = confirm("Press a button!");
if (r == true) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = txt;
}
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<html>
<head>
<title>Are you sure?</title>
<script>
function areYouSure() {
var res = confirm("Are you sure?");
return res; //true or false
}
</script>
</head>
<body>
<form method="POST" action="action_page.php">
<!--
...
-->
<input type="submit" onclick="return areYouSure()"/>
</form>
</body>
</html>

How to use implement a text input form using JavaScript in HTML

I am trying to use JavaScript in an online examination assignment in HTML. As a requirement of the project, we have to use text input forms as well as radio buttons and the like. I have dealt with the part of radio buttons but for some reason my text input forms do not work. My problem will be clearly stated using this code snippet from the main project:
<html>
<head>
<title></title>
<script type="text/javascript">
var test, name, matr, myname, count = 0;
function form(){
test = document.getElementById("test");
test.innerHTML = "Count = "+count;
test.innerHTML += "<form> \
First name:<br> \
<input type='text' name='name'><br>\
<button onclick='check()'>Submit Answer</button>";
}
function check(){
myname = document.getElementsByName("name");
if (myname[1].value == "myname")
{
count++;
}
form();
}
window.addEventListener("load", form, false);
</script>
</head>
<body>
<div id = "test"></div>
</body>
</html>
What this code aims to do is that when the user inputs "myname" into the form called 'First name' and clicks 'Submit', the counter on the top should increment.
Can someone please shed some light on what I am doing wrong and how it may be resolved.
As Pluto mentioned, arrays in javascript start at 0. You can also look at tinkering with the form element. It is not closed nor is the type, get or post specified. I got it working in the example below by removing the form completely. This is because the button press was trying to submit the form and therefore load a new page.
https://jsfiddle.net/jpm68eub/
var test, name, matr, myname, count = 0;
function form() {
test = document.getElementById("test");
test.innerHTML = "Count = " + count;
test.innerHTML += "</br> First name:<br> \
<input type='text' name='name'><br>\
<button onclick='check()'>Submit Answer</button>";
}
function check() {
myname = document.getElementsByName("name");
if (myname[0].value == "myname") {
count++;
}
form();
}
form();
you need to prevent the default action of the onclick event. To do this, try something like this:
function check(e){
e.preventDefault();
myname = document.getElementsByName("name");
if (myname[0].value == "myname")
{
count++;
}
form();
}
the above user was also correct about where javascript arrays start (they start at 0)

Why does this think it's correct?

I'm new to js and I have this very simple code. It's supposed to be a login, and it's not working. I don't need any tips on making it better, I'm planning to do that when this starts to work.
<!DOCTYPE html>
<head> Sign-in </head>
<body>
<script type="text/javascript">
var em = prompt("Enter E-mail Here:")
if(em = "I hid this to prevent spam"){
var pa = prompt("Enter Password Here:")
if(pa = "jct28if5"){
alert("Welcome!")
}
else{
alert("Incorrect password!")
}
}
else {
alert("Invalid e-mail!")
}
</script>
</body>
</html>
What it's doing now is no matter what, it thinks that the correct e-mail and password were used. Could somebody help?
I've fixed your code up a bit. Some things to note.
You can't just put raw content in the <head>.
Your password is in the raw source of the page, so anyone can view the page source and see what the correct password is. That's an absolutely horrible design. Passwords should be passed to server side where they're checked for validity.
In C like programming language such as Javascript, == tests for equality and will return a boolean. The = sign assigns a value to a variable.
<!DOCTYPE html>
<head>
<title>Sign-in
</title>
<script type="text/javascript">
var em = prompt("Enter E-mail Here:")
if(em == "I hid this to prevent spam"){
var pa = prompt("Enter Password Here:")
if(pa == "jct28if5"){
alert("Welcome!")
}
else{
alert("Incorrect password!")
}
}
else {
alert("Invalid e-mail!")
}
</script>
</head>
<body>
</body>
</html>
Just one addition:
== checks value
=== checks value and type
Someone who deactivates js or doesn't support it like curl/wget and others, will not be stopped by this, except you load the whole website with js, what might be stupid cause of search engines might not index the content though.
Hope this helps.
fixed
var em = prompt("Enter E-mail Here:")
if(em === "I hid this to prevent spam"){
var pa = prompt("Enter Password Here:")
if(pa === "jct28if5"){
alert("Welcome!")
}
else{
alert("Incorrect password!")
}
}
else {
alert("Invalid e-mail!")
}
You use a single = when you're assigning a variable a value. like var x = 1.
But if you want to check equality, use ===. like if(x ===1)

Display the form again?

I want to ask about the form in Javascript.
I want to do a game where the user enters the correct word, then an alert message will appear for this correct word. When the user does the first word correct, the program will display another word (to be corrected). But the problem which I faced that I can't make the form display again to continue the game.
I used:
var d = document.getElementById("form1"); d.style.visibility = "visible";
but it doesn't work!
This is my code:
<head>
<title>Word Decoder</title>
<script type="text/javascript">
function checkWord(word, score)
{
var ok = words[score].valueOf();
var ok1 = document.getElementById("wordid");
if(ok1.value == ok)
{
score ++;
alert("Correct, your score is: " + score);
var d = document.getElementById("form1");
d.style.visibility = "visible";
return false;
}
else
{
alert("Wrong Spelling");
return false;
}
}
</script>
</head>
<body>
<script type="text/javascript">
var words = new Array ("apple", "orange", "banana", "manago", "table");
var reWords = new Array ("alpep", "ergano", "aaabnn", "goamna", "lbeat");
var count = 0;
var score = 0;
"</br>";
</script>
<form id="form1">
<br>
<dir id="displayForm"
style="position: relative;
visibility: visible;
display: block">
<h3><b> <script> document.write(reWords[score]);</script> </b></h3>
<br>
Enter the correct word: <input type="text" value="" id="wordid"/>
<input type="submit"
value="Check Answer ??"
onclick="return checkWord(wordid, score);" />
</dir>
</form>
</body>
Again: I want the game will display a scrambled word and the user must unscrambled the word to move to the other word. The problem is I can't display the form again to make the user unscrambled the second, third etc. words.
Use d.style.display="none" to hide and d.style.display="block" to show.
Think your post got mangled, I don't see where you are hiding it in the first place.. Also, avoid using document.write if you don't need it... inject the element or use .innerHTML if you need to, but not document.write.

Categories

Resources