-1

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.

ash
  • 11
  • 2

2 Answers2

3

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>
Community
  • 1
  • 1
Satpal
  • 132,252
  • 13
  • 159
  • 168
0

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.

Community
  • 1
  • 1
ankurJos
  • 496
  • 4
  • 16