What is causing an empty box to appear due to padding? Is there a way to conceal it

There seems to be an issue with adding padding to the results id div box. The padding is causing a blank yellow box to appear at the bottom before any results are submitted. I've tried to hide this box without success by adding a displayResult() function at the end of my script with a display:none; property, but it ended up hiding it completely.

I could really use some help in figuring out how to solve this problem.

function calculateScore() {
  const form = document.forms["form"];
  const questions = form.elements["quiz"];
  const pointValue = 1;
  let score = 0;

  for (i = 0; i < questions.length; i++) {
    if (questions[i].checked) {
      score += pointValue;
    }
  }
  return score;
}

function displayTotal() {
  const totalScore = calculateScore();
  document.getElementById("result").innerHTML = getFeedback(totalScore);
}

// Feedback messages based on score
const zeroToOne = "<b>Results</b>: It is amazing that you already know all of these things about yourself and didnt need to take the quiz. Maybe you just wanted to see all of the possible result responses? Well played!";
const twoToSeven = "<b>Results</b>: I see that among your many talents and attributes, humility is still part of your charm!";
const eightToThirteen = "<b>Results</b>: It is amazing that you already know all of these things about yourself. Please consider joining our community of engaged honors students like you!";
const fourteenToNineteen = "<b>Results</b>: Did you take this quiz just to show off how well you’d fit into the CC Honors community? Wow, I mean just wow!";
const twentyToTwentyFive = "<b>Results</b>: I see that your streak of dominating assessments is intact. You already knew the outcome when you began the quiz. Way to rock it!";

function getFeedback(score) {
  if (score <= 1) {
    return zeroToOne;
  } else if (score >= 2 && score <= 7) {
    return twoToSeven;
  } else if (score >= 8 && score <= 13) {
    return eightToThirteen;
  } else if (score >= 14 && score <= 19) {
    return fourteenToNineteen;
  } else if (score >= 20 && score <= 25) {
    return twentyToTwentyFive;
  }
}

// Event listener for submit button
document.getElementById("submit").onclick = displayTotal;

// Reset button function
function resetButton() {
  document.getElementById("result").innerHTML = "";
}

// Function to display result
function displayResult() {
  const resultBox = document.getElementById("result");
  resultBox.style.display = "";
}
.quiz-form {
  margin-left: auto !important;
  margin-right: auto !important;
  max-width: 700px;
}

#form {
  text-align: left;
}

.section {
  display: flex;
  align-items: center;
}

label {
  margin-left: .7rem;
  margin-bottom: 0;
}

#submit {
  background-color: #2f1400;
  color: #fff;
  border: none;
  font-weight: bold;
  padding: 10px 15px;
  border-radius: 8px;
}

#submit:hover {
  background-color: #5d3f24;
}

#reset:hover {
  background-color: #5d3f24;
}

#reset {
  background-color: #2f1400;
  color: #fff;
  border: none;
  font-weight: bold;
  padding: 10px 15px;
  border-radius: 9px;
}

input[type="checkbox"] {
  min-width: 17px;
  min-height: 17px;
  cursor: pointer;
}

#result {
  background-color: #ffda01;
  /* display:none; */
  padding: 10px;
}
<div class="quiz-form">
  <form id="form" name="form">
    <fieldset id="controls">
      <div class="quiz-questions">
        <div class="section">
          <input type="checkbox" name="quiz" class="quiz" value="point" />
          <label> I enjoy reading for fun.
                    </label>
        </div>
        <br>
        <div class="section">
          <input type="checkbox" name="quiz" class="quiz" value="point" />
          <label> I like to write.
                    </label>
        </div>
        <br>
        <!-- More checkboxes and labels can be added here -->

      </div>
      <br>

      <p>
        <input type="button" onclick="displayResult()" name="submit" id="submit" value="Submit" />
        <input type="reset" onclick="resetButton()" id="reset" value="Reset">
      </p>

      <div id="result"></div>

    </fieldset>
  </form>

  <br>

Answer №1

Consider hiding the result by setting its style to visibility: hidden after setting the result, and then make it visible again when the reset button is pressed.

Answer №2

Initially, I conceal the result ID in CSS and unveil it once the results are available. Additionally, I made modifications to some HTML and JS elements.

The displayResult function has been eliminated from both the JS and HTML sections, and the getTotal function has been updated as follows:

function getTotal() {
  const totalScore = getScore();
  var result = document.getElementById("result");
  result.innerHTML = getComment(totalScore);
  result.style.display = "block";
}

First, we store the result in a variable, then update its content using the original innerHTML line, and finally change its style to block to make it visible.

The reset function has also been revised to hide the result container. Since the content of the result is replaced each time, there's no need to set it to an empty string.

I've included functions for calculating scores and providing corresponding comments based on the score range.

Finally, we have defined styling rules for various elements within the quiz form to enhance its appearance and functionality.

Answer №3

You were on the right path by using display: none;. To show the result div upon submission and hide it upon resetting, you simply need to dynamically change the style from JavaScript:

function getScore() {
  const form = document.forms["form"];
  const quest = form.elements["quiz"];
  const pointValue = 1;
  let score = 0;

  for (i = 0; i < quest.length; i++) {
    if (quest[i].checked) {
      score = score + pointValue;
    }
  }
  return score;
}

function getTotal() {
  
  const totalScore = getScore();

  // REFERENCE TO THE RESULT DIV ELEMENT
  const resDiv = document.getElementById("result");

  // SHOW THE RESULT DIV
  resDiv.style.display = 'block';

  resDiv.innerHTML = getComment(totalScore);
}

const zeroToOne =
  "<b>Results</b>: It is amazing that you already know all of these things about yourself and didnt need to take the quiz. Maybe you just wanted to see all of the possible result responses? Well played!";
const twoToSeven =
  "<b>Results</b>: I see that among your many talents and attributes, humility is still part of your charm!";
const eightToThirteen =
  '<b>Results</b>: It is amazing that you already know all of these things about yourself. Please consider joining our community of engaged honors students like you!';
const fourtTonNine =
  '<b>Results</b>: Did you take this quiz just to show off how well you’d fit into the CC Honors community? Wow, I mean just wow!';
const twentyToFive =
  '<b>Results</b>: I see that your streak of dominating assessments is intact. You already knew the outcome when you began the quiz. Way to rock it!';

function getComment(score) {
  if (score <= 1)
    return zeroToOne;
  else if (score >= 2 && score <= 7)
    return twoToSeven;
  else if (score >= 8 && score <= 13)
    return eightToThirteen;
  else if (score >= 14 && score <= 19)
    return fourtTonNine;
  else if (score >= 20 && score <= 25)
    return twentyToFive;
}


document.getElementById("submit").onclick = getTotal;


function resetButton() {
  // REFERENCE TO THE RESULT DIV ELEMENT
  const resDiv = document.getElementById("result");

  // HIDE THE RESULT DIV
  resDiv.style.display = 'none';

  resDiv.innerHTML = "";
}


function displayResult() {
  const hide = document.getElementById("result");
  hide.style.display = "";
}
.quiz-form {
  margin-left: auto !important;
  margin-right: auto !important;
  max-width: 700px;
}

#form {
  text-align: left;
}

.section {
  display: flex;
  align-items: center;
}

label {
  margin-le...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Cannot update VUEjs array following the splice operation

My array is only updating in the console and not in the DOM. I've already tried using :key but it's still not working. Here is my code: <div style="margin-top: 5px;" v-for="(file, index) in editedItem.file_name" ...

Where can I find the JavaScript code that controls the button function?

Is there a method to identify the trigger that activates a button's specific action and page refresh, such as this example: <input type="submit" name="name" value="some value" id="mt1_main_btn" class="btn_next"> Simply copying the button does ...

Tips on validating ASP.NET gridview textbox with javascript during the update process:

I've implemented a gridview on my aspx page: <asp:GridView ID="gvPhoneBook" runat="server" AutoGenerateColumns="false" ShowFooter="true" DataKeyNames="PhoneBookID" ShowHeaderWhenEmpty="true" OnRowCommand="gvPh ...

What is the purpose of the "modal-backdrop fade show" element remaining visible after the associated component is unmounted, and what is the best way to eliminate or disable this div?

Scenario I have a Vue component that includes a child component responsible for displaying a modal. Toggling the isShowModal boolean either through a button click or Vue devtools successfully displays and hides the modal as expected. However, upon tryin ...

Dealing with multiple parameters within the app.param() function

Currently, I am developing an API using Express.js and facing a challenge in implementing an app.param() function for handling the id parameter in a GET request: app.param('id', (req, res, next, id) => { const envelopeIndex = Number(id); ...

What is the most effective way to show the current date on a webpage: utilizing JavaScript or PHP?

Looking to show the current date and time on a webpage. There are two potential methods to achieve this: (1) Using PHP, for example: <?php echo date('Y-m-d H:i:s');?> (2) ... or JavaScript, like so: <div> <script>document.wri ...

Interactive radio button that only registers the most recent click

Homepage.jsx const Homepage = () => { const [categories, setCategories] = useState([]) const [products, setProducts] = useState([]) const [selected, setSelected] = useState("all") const getAllCategories = async() => { try{ ...

Error: React js app has crashed. Currently waiting for file changes before restarting

I recently began using nodemon and started working on a small sample project. However, when I try to launch the server using sudo npm run dev, I encounter the following error: [nodemon] app crashed - waiting for file changes before starting... The error ...

How can we ensure that an enum is accessible throughout the entire meanjs stack?

Currently, I am exploring the meanjs technology stack and facing a challenge in creating a centralized enum array that can be accessed throughout the project, from MongoDB to Angular. Can anyone suggest a smart solution for accomplishing this task? ...

Could there be a more efficient method to enable support for all video formats?

I have a case statement in my video validation function that checks for specific file extensions of video formats. However, I am wondering if there is a shorter way to write the code in order to allow all video formats instead of creating a long list of al ...

Utilizing the power of HTML5 drag and drop functionality in conjunction with Angular Material 2's md

When working with Angular Material 2 and attempting to enable reordering of list elements, I encountered an issue where the functionality works perfectly for li-tag but fails with md-list-item. Why is that? Here is a snippet of my template: <md-nav-li ...

Navigate through a series of div elements using Jquery

I need help figuring out how to make the window scroll between different divs in a sequence. The issue is that my current code only works for one specific div at a time. $('.down_arrow').click(function(e){ $('html, body') ...

How to add a subtle entrance animation to text (demonstration provided)

Apologies for the brevity, but I could really use some assistance with replicating an effect showcased on this particular website: My understanding is that a "fadeIn" can be achieved using jQuery, however, I am at a loss as to how to implement the 3D effe ...

Is Firefox the only browser where the webpage is displayed off-center?

I've encountered a strange issue with my website that I can't seem to figure out. Despite searching extensively on Google and Stackoverflow, I haven't come across anyone else facing the same problem. During testing in different browsers lik ...

Open $_POST in a new tab that has been edited for your convenience

<form method="post" target="_blank" action="battle.php" onsubmit="window.open('battle.php','','width=700,height=500,toolbar=0,menubar=0,location=0,status=0,scrollbars=0,resizable=0,left=30,top=0');" > < ...

Adjusting the width of row items in Angular by modifying the CSS styles

I am envisioning a horizontal bar with items that are all the same width and evenly spaced apart. They can expand vertically as needed. Check out the updated version here on StackBlitz https://i.sstatic.net/MFfXd.png Issue: I am struggling to automatica ...

Unlock the Power of Heroku: Leveraging Node.js to Share Environment Variables Across JavaScript Pages

Currently, I am following the 'getting started' guide on the Heroku webpage. As part of this process, I have cloned their tutorial repository and decided to add my own index.html and app.js files to the existing /public folder. The directory str ...

JavaScript - Modify input character prior to appending it to the text area

I am working on creating a virtual keyboard using jQuery. Whenever I press 'a' in the textarea, I want it to display 'z' instead. In my investigation of typing a letter in the textarea, I discovered the following sequence: keyDown ev ...

Javascript - Incorporate a hyperlink into my Flickr Api image query

I am struggling with incorporating a link around the image generated by this request due to my limited API knowledge. Below is the current function responsible for displaying the album images. To see a functional version, please refer to the provided fidd ...

What can you do to prevent a div from taking up the entire page if its height is not specified?

Currently, I am experiencing an issue with my layout. I have a hidden div with a fixed position that becomes visible when a button on the page is clicked. Inside this div, there is a table of buttons for the user to choose from. The problem arises when I ...