Marc
Marc

Reputation: 13

Attempt to display hidden text, text keeps disappearing

I'm trying to display one day - depending upon the button clicked. Ideally I'd use radio input for the 3 days, but the buttons were getting me closer. When I click a button, the text appears and then quickly disappears. Obviously I'm doing something wrong. TIA, Marc

<!DOCTYPE html>
<html lang="en">
 <head>
  <title>Document</title>
 </head>
 <body>

<form>
<button onclick="changeDay('thu');" style="width: 100%"> Thursday Performance</button><br>
<button onclick="changeDay('fri');" style="width: 100%"> Friday Performance</button><br>
<button onclick="changeDay('sat');" style="width: 100%"> Saturday Performance</button><br>

 <div id="thu" style="display:none;">
    This is Thursday
    </div>
 <div id="fri" style="display:none;">
    This is Friday
    </div>
 <div id="sat" style="display:none;">
    This is Saturday
    </div>

<script language="JavaScript">

function changeDay(show_day) {
    document.getElementById('thu').style.display = "none";
    document.getElementById('fri').style.display = "none";
    document.getElementById('sat').style.display = "none";
    document.getElementById(show_day).style.display = "block";
}
</script>
 </body>
</html>

Upvotes: 1

Views: 49

Answers (1)

RDU
RDU

Reputation: 1071

It's because you are wrapping your buttons inside a <form> tag, and it's also not closed.

I'm not sure but I think because you are wrapping the buttons inside a form, when you click a button, the form tries to submit data, and because it's not set up correctly it redirects causing an error 404 in my testing.

You don't need to use a form in this case, when you just call functions that manipulate data, forms are used usually when sending data.

MDN Docs on form - The HTML form element represents a document section containing interactive controls for submitting information.

Snipped without the form tag

<!DOCTYPE html>
<html lang="en">
 <head>
  <title>Document</title>
 </head>
 <body>

<button onclick="changeDay('thu');" style="width: 100%"> Thursday Performance</button><br>
<button onclick="changeDay('fri');" style="width: 100%"> Friday Performance</button><br>
<button onclick="changeDay('sat');" style="width: 100%"> Saturday Performance</button><br>

 <div id="thu" style="display:none;">
    This is Thursday
    </div>
 <div id="fri" style="display:none;">
    This is Friday
    </div>
 <div id="sat" style="display:none;">
    This is Saturday
    </div>

<script language="JavaScript">

function changeDay(show_day) {
    document.getElementById('thu').style.display = "none";
    document.getElementById('fri').style.display = "none";
    document.getElementById('sat').style.display = "none";
    document.getElementById(show_day).style.display = "block";
}
</script>
 </body>
</html>

Upvotes: 3

Related Questions