I want to use RegExp in else if(){} statements. How is it done?
I want to do:
If the user's value (prompt) is equal to "javascript" or "JaVaScRipT" then let the else if statement work.
<body>
<button onclick="javascript:notfic();">Click</button>
<p id="result"></p>
<script>
"use strict"
function notfic(){
let message="", result, del;
result = document.querySelector('#result');
del = prompt("Please, enter your answer");
if (del == null || del==""){
message = "You must write answer";
}else if(del == /javascript/i){
message = "You enter correct answer. Your answer is: <br> " + del;
}else{
message = "Sorry, your answer is wrong. Your answer is: <br>" + del;
}
result.innerHTML = message;
}
</script>
</body>
Your you need to call the test method:
else if(/javascript/i.test(del))
Read this for more info
Related
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.
I'm passing through some issues while trying to make this code work.
The JavaScript part :
var name = document.getElementById("name").value ;
var msg = document.getElementById("msg").value ;
var date = new Date();
function post() {
if (name === "") {
alert("You are missing something :)");
document.getElementById("name").focus();
}
else if (msg === "") {
alert("You are missing something :)");
document.getElementById("msg").focus();
}
else {
document.getElementById("content").innerHTML += ("<p id='post'>Name :. " + name + "</p><br><p id='post'>Comment :. " + msg + "</p><br><p>" + date + "</p>");
alert("Successfully posted :)");
}
}
And the body part :
<div id="content">
<h1>:. Welcome to the discussion .:</h1>
<br><br>
<p>The topic is : The structure of this website.</p>
<br>
Name/Nickname :.<br><input type="text" value="" id="name" maxlenght="32">
<br>
<p>
Message :.<br><textarea id="msg" cols="40" rows="5"></textarea>
<p>
<input type="button" value="Post" onClick="javascript:post()">
</div>
I get some issues when I press the 'post' button, it shows up the alert even being with or without letters on the 'name' and 'msg' inputs. And I can't see if the 'else' part will work because I can't even pass through the first part :c . I tried everything, but no success, hope someone can give me a light.
This section only gets run once:
var name = document.getElementById("name").value ;
var msg = document.getElementById("msg").value ;
var date = new Date();
If you want to recheck the name value when post is called, you should have name be reassigned to document.getElementById("name").value within the post function.
I have a php page the verifies the username users type in, and echo's back "available!" if its available into a div called "feedback". now I have this JavaScript that I want to check to see if the "feedback" div says "available! and echo "username good" into the "check" div if it is. but it doesn't work and i don't know why.
<script type='text/javascript'>
function check_info(){
var username_good = document.getElementById('feedback').value;
if(username_good == "available!"){
document.getElementById("check").innerHTML = "username good";
}
else{
document.getElementById("check").innerHTML = "bad";
}
}
</script>
A div doesn't have a value property, you need to use innerHTML:
var username_good = document.getElementById('feedback').innerHTML;
Fiddle for the same added.
<div id="feedback">test</div>
<div id="check"></div>
<input type="button" onclick="javascript:check_info()" value="Validate">
function check_info(){
var username_good = document.getElementById('feedback').innerHTML;
if(username_good !== ""){
document.getElementById("check").innerHTML = "username good";
}
else{
document.getElementById("check").innerHTML = "bad";
}
}
I am working on a "guess my number" game and have ran into a problem. My game is supposed to select a random integer between 1 and 10 and allow the user to guess until they guess the correct number. After each guess, I'm supposed to display a message telling whether their guess was too high, too low, correct, or if they'd guessed that number before. I had the game working (except for displaying the array of previously guessed numbers) by using alerts to display the whether the user was too high, low, correct, etc like this.
if (guess == this.num) {
alert("Correct! It took you " + turns " tries to guess my number.");
...
}
However, going back over the directions I see that we are not supposed to user alerts or any other kinds of pop-ups. So I need to figure out how to display these messages on the screen rather than in an alert box.
Here is how I've attempted to do this without the use of alerts, but now the game is not working at all (nothing happens when I click either of the buttons):
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>Guess My Number</title>
<script type="text/javascript">
var tries = [];
var game = {
num : 0,
turns : 1,
reset : function() {
this.turns = 1;
this.newNum();
},
newNum : function() {
this.num = parseInt(Math.random() * 10) +1;
},
guessNumber : function(guess) {
try {
guess = parseInt(guess);
}
catch(e) {
alert("Enter a guess!");
this.turns++;
return false;
}
if (guess == this.num) {
document.getElementById("result").value = "Correct! It took you " + this.turns + " tries to guess my number.");
alert("Correct! It took you " + this.turns + " turns to guess my number.");
tries.push(guess);
document.querySelector("#tries").textContent = tries.join(', ');
document.getElementById("guess").value = " ";
return true;
}
else if(guess > this.num) {
document.getElementById("result").value = "Your guess is too high. Try again.";
alert("Your guess is too high. Try again.");
document.querySelector("#tries").textContent = tries.join(', ');
this.turns++;
document.getElementById("guess").value = " ";
return false;
}
else if(tries.indexOf(guess) != -1) {
document.getElementById("result").value = "You have already guessed this number. Try again.";
this.turns++;
document.getElementById("guess").value = " ";
return false;
}
else {
document.getElementById("result").value = "Your guess is too low. Try again.";
document.querySelector("#tries").textContent = tries.join(', ');
tries.push(guess);
this.turns++;
document.getElementById("guess").value = " ";
return false;
}
}
};
function guessNumber() {
var guess = document.getElementById("guess").value;
game.guessNumber(guess);
document.getElementById("guess").value = " ";
}
function resetGame() {
game.reset();
document.getElementById("guess").value = " ";
}
resetGame();
</script>
</head>
<body>
<h1>Would You Like To Play A Game?</h1>
<h2>Thank you for checking out my game. Good luck!</h2>
<h3>Created by Beth Tanner</h3>
<h2>Directions:</h2>
<p>
The game is very simple. I am thinking of a number between 1
and 10. It is your job to guess that number. If you do not guess
correctly on your first attempt, don't worry, you can keep guessing
until you guess the correct number.
</p>
<p>
Your Guess: <input type="text" id="guess" size="10" />
<br />
<input type="button" value="Sumbit Guess" onclick="guessNumber()" />
<input type="reset" value="Reset Game" onclick="resetGame()"/>
</p>
<h3>How Did You Do?:</h3>
<p>
<input type="hidden" id="result" size="20" />
</p>
<h3>Here Are Your Guesses So Far:</h3
</body>
</html>
Is there any simple way to do this. I want the messages to display in a hidden text filed below the heading "How did you do?:" if that makes it a little clearer.
Here is a jsfiddle I made with my most recent code, http://jsfiddle.net/3p3f86fj/6/
You should add a div to your body with a unique ID, like <div id='result'></div> and then in your JS, reference it by getting the document by ID and your functions should change the text of the div to whatever you need it to be. Make a function to change the name if you want to abstract some of the logic away.
It's broken because of this line I believe:
document.getElementById("result").value = "Correct! It took you " + this.turns + " tries to guess my number.");
You have a stray ) at the end.
I'm looking into other issues I see now.
I want to know how to alert "Oops, looks like you didn't enter anything", if the user has
entered "Enter your name". i have an if and and elseif but i don't know if else would work for it. Here is my code
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body style="background-color: silver">
<script>
var name=prompt("Enter your name", "Enter your name")
if (name !== '') {
alert("Welcome" + " " + name)
} else if(name !== false) {
prompt("Oops, looks like you didn't enter anything");
}
</script>
</body>
<html>
This method defines a function getName() which takes the same arguments as prompt(). If no default value is specified, it uses the question that was passed to it. It then asks the user for their name using these values. If the user returns a response that is unsatisfactory, i.e. is falsy (name === '', name === null, etc) or equivalent to the prompt we gave them, we pop a new prompt with an error message but the same default message.
function getName(ques, def) {
def = def || ques; // Make default param optional
var name = prompt(ques, def);
if (name && name !== '' && name != def) {
return name;
} else if(name !== false) {
return getName("Oops, looks like you didn't enter anything", def);
}
};
var name = getName("Enter your name");
alert('Your name is: ' + name);
Demo: http://cdpn.io/rlJGj
Be careful with this from a user experience perspective. Its downright horribly for many reasons. If the user hits cancel, this will prompt them until they enter an acceptable value and press ok. It doesn't make for the best user experience, a quite bad one, in fact.
<script>
var name=prompt("Enter your name", "Enter your name")
if (name!=='' && name!=='Enter your name') {
alert("Welcome" + " " + name)
} else if(name!==false) {
prompt("Oops, looks like you didnt enter anything");
}
</script>
Demo
If you look at the definition of JavaScript's prompt() method, you could see that the second parameter is the default text that the method should return in case the user has not entered anything.
Try this instead:
var name = prompt("Enter your name");
if (name === "") {
prompt("Oops, looks like you didn't enter anything");
} else if(name != null) {
alert("Welcome" + " " + name);
}
Hope this helps! Live demo here.
else if(name !== false) will always be true.
since name will never hold the value true; === doesn't do type conversion.
So a little clean up:
var pHolder = "Enter your name"
var name=prompt("Enter your name", pHolder )
if(!name ||name == pHolder){
alert("Oops, looks like you didnt enter anything");
}
else{
alert("Welcome" + " " + name)
}