Using HTML and JavaScript to show the output of a loop by invoking a <div> element from HTML to JS

In a scenario where the user can input both the Total Quantity and the Total Pass and Total Fail, a function has been created. This function initiates a loop to enter pass scores based on the number of Total Pass inputs.

The goal is to avoid displaying the line Enter The Score : within the JavaScript function's loop. Instead, it's desired for the function to retrieve a div from the HTML itself.

For instance, the

<div id="outputPass"><p>Enter the score : <input type="text" /></p></div>
should be invoked in the loop function located in the
document.getElementById('btnPass').onclick = function()
.

There are comments inserted in the code section:

document.getElementById('btnPass').onclick = function() {
  var totalIterations = parseInt(document.getElementById('inputPass').value);
  var output = document.getElementById('outputPass');
  var quantity = document.getElementById('quantity').value;
  output.innerHTML = '';

  if (quantity < totalIterations) {
    alert("Invalid Input, Pass Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
  } else {
    for (var i = 1; i <= totalIterations; i++) {
      var item = document.createElement('div');
      //Call <div> from HTML 
      item.innerHTML = "";
      output.appendChild(item);
    }
  }
};

document.getElementById('btnFail').onclick = function() {
  var totalIterations = parseInt(document.getElementById('inputFail').value);
  var output = document.getElementById('outputFail');
  var quantity = document.getElementById('quantity').value;
  output.innerHTML = '';

  if (quantity < totalIterations) {
    alert("Invalid Input, Fail Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
  } else {
    for (var i = 1; i <= totalIterations; i++) {
      var item = document.createElement('div');
      //Call <div> from HTML
      item.innerHTML = "";
      output.appendChild(item);
    }
  }
};

function togglePass() {
  var x = document.getElementById("passDiv");

  if (x.style.display === "block") {
    x.style.display = "none";
  } else {
    x.style.display = "block";
  }
}

function toggleFail() {

  var y = document.getElementById("failDiv");

  if (y.style.display === "block") {
    y.style.display = "none";
  } else {
    y.style.display = "block";
  }
}
.display {
  display: none;
}
<form method="post" name="form">
  <p>Enter the quantity : <input type="text" id="quantity" name="quantity" /></p><br />

  <input type="button" value="Pass" onclick="togglePass()">
  <input type="button" value="Fail" onclick="toggleFail()">

  <div id="passDiv" class="display">
    <p>Enter Total Pass : <input type="text" id="inputPass" name="inputPass" />&nbsp<input type="button" value="Key In Score" id="btnPass" onclick="return validate();"></p><br />
    <!--This Div-->
    <div id="outputPass">
      <p>Enter the score : <input type="text" /></p>
    </div>
    <br />
    <input type="button" value="DONE">
  </div>
  <br />

  <div id="failDiv" class="display">
    <p>Enter Total Fail : <input type="text" id="inputFail" />&nbsp<input type="button" value="Key In Score" id="btnFail"></p><br />
    <!--This Div-->
    <div id="outputFail">
      <p>Enter the score : <input type="text" /></p>
    </div>
    <br />
    <input type="button" value="DONE">
  </div>

</form>

Answer №1

To achieve your desired outcome, consider implementing the following modifications:

  • Start by assigning an id of pscore/fscore (for pass and fail respectively) to the <p></p> tags and hiding them initially.

<p id="fscore" style="display:none">Enter the score : <input type="text" /></p>

  • In your JavaScript code, access these elements as variables pscore and fscore respectively (ensure they are globally declared outside).

    var pscore = document.getElementById('pscore');
    var fscore = document.getElementById('fscore');

  • Subsequently, in the iterations, create a copy of the pscore/fscore, assign a class of pscore/fscore to the <p></p> tags, remove the id of pscore/score (to prevent duplicate IDs), change the display to block, and append it to the output container using the following method:

    var cln = pscore.cloneNode(true);
          cln.style.display="block"; 
          cln.className ="pscore";
          cln.removeAttribute("id");
          item.appendChild(cln);

    var cln = fscore.cloneNode(true);
          cln.style.display="block"; 
          cln.removeAttribute("id");
          cln.className ="fscore";
          item.appendChild(cln);

var pscore = document.getElementById('pscore');
var fscore = document.getElementById('fscore');
document.getElementById('btnPass').onclick = function() {
  var totalIterations = parseInt(document.getElementById('inputPass').value);
  var output = document.getElementById('outputPass');
  var quantity = document.getElementById('quantity').value;
  output.innerHTML = '';

  if (quantity < totalIterations) {
    alert("Invalid Input, Pass Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
  } else {
    for (var i = 1; i <= totalIterations; i++) {
      var item = document.createElement('div');
      //Obtain <div> from HTML
      var cln = pscore.cloneNode(true);
      cln.style.display = "block";
      cln.className = "pscore";
      cln.removeAttribute("id");
      item.appendChild(cln);
      output.appendChild(item);
    }
  }
};

document.getElementById('btnFail').onclick = function() {
  var totalIterations = parseInt(document.getElementById('inputFail').value);
  var output = document.getElementById('outputFail');
  var quantity = document.getElementById('quantity').value;
  output.innerHTML = '';

  if (quantity < totalIterations) {
    alert("Invalid Input, Fail Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
  } else {
    for (var i = 1; i <= totalIterations; i++) {
      var item = document.createElement('div');
      //Obtain <div> from HTML
      var cln = fscore.cloneNode(true);
      cln.style.display = "block";
      cln.className = "fscore";
      cln.removeAttribute("id");
      item.appendChild(cln);
      output.appendChild(item);
    }
  }
};

function togglePass() {
  var x = document.getElementById("passDiv");

  if (x.style.display === "block") {
    x.style.display = "none";
  } else {
    x.style.display = "block";
  }
}

function toggleFail() {

  var y = document.getElementById("failDiv");

  if (y.style.display === "block") {
    y.style.display = "none";
  } else {
    y.style.display = "block";
  }
}
.display {
  display: none;
}
<form method="post" name="form">
  <p>Enter the quantity : <input type="text" id="quantity" name="quantity" /></p><br />

  <input type="button" value="Pass" onclick="togglePass()">
  <input type="button" value="Fail" onclick="toggleFail()">

  <div id="passDiv" class="display">
    <p>Enter Total Pass : <input type="text" id="inputPass" name="inputPass" />&nbsp;<input type="button" value="Key In Score" id="btnPass"></p><br />
    <!--This Div-->
    <div id="outputPass">
      <p id="pscore" style="display:none">Enter the score : <input type="text" /></p>
    </div>
    <br />
    <input type="button" value="DONE">
  </div>
  <br />

  <div id="failDiv" class="display">
    <p>Enter Total Fail : <input type="text" id="inputFail" />&nbsp;<input type="button" value="Key In Score" id="btnFail"></p><br />
    <!--This Div-->
    <div id="outputFail">
      <p id="fscore" style="display:none">Enter the score : <input type="text" /></p>
    </div>
    <br />
    <input type="button" value="DONE">
  </div>

</form>

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

Fullcalendar time correction with Ajax and Flask: Step-by-step guide

After creating an appointment on the calendar, the start and end time display correctly. However, upon reloading the page, the datetime appears different on both the calendar and in the database. For instance, if I schedule an appointment from 09:00 AM to ...

What is the best way to create a command that updates the status in Discord using discord.js?

I'm currently working on a command for my Discord bot using discord.js. The purpose of this command is to change the bot's status whenever an admin of the server triggers it. I've attempted to create the command, but unfortunately, it's ...

Issue with JQuery Ajax: Some users experiencing failure with ajax requests (response code 0)

I've implemented an ajax-based login system where users input their username/password and the data is asynchronously sent to a PHP script for validation. Once validated, the user is logged in or an error message is returned in JSON format. However, I ...

Formatting of large numerical values with jQuery

I have a huge table with numbers and other data. I want to color the large numbers based on their value in decimal, hundreds, thousands, and millions. For example: <tr> <td class="numColour">20,000,365.00 ISK</td> <td class="nu ...

Learn how to automatically set the checked state of a radio button by toggling another radio button

I have two sets of radio buttons, each with four options. The first set has no default selection (unchecked) using jQuery, while the second set has the first option checked by default. What I'm looking to achieve is that when a radio button in the f ...

Connect my asp.net grid view to JavaScript using AJAX

I am seeking guidance on how to bind my gridview from JavaScript in an ASP.NET web forms application. My objective is to click a linkbutton within my gridview and have it trigger a modalpopup that displays another gridview. Here are snippets of my code s ...

The proper way to define an event delegator's syntax

Typically, when you want to handle a button click event, you would do so like this: $(document).ready(function() { $("button").click(function() { doSomething(); }); }); However, in the scenario of an event delegator, you may need to respon ...

Having trouble with the GitHub publish action as it is unable to locate the package.json file in the root directory, even though it exists. Struggling to publish my node package using this

I've been struggling to set up a publish.yml file for my project. I want it so that when I push to the main branch, the package is published on both npm and GitHub packages. However, I am facing difficulties in achieving this. Here is the content of ...

Do not dismiss Bootstrap Modal when a particular button inside it is clicked

I have created a modal that contains a form with 5 buttons: Submit, 2 Close buttons, and 2 buttons for an input number spinner where users can adjust the quantity using the "+" and "-" buttons. However, every time the user clicks on the "+" or "-" button, ...

Issue: The keyword in React/React-Native is returning a boolean value instead of the expected element object

I've recently delved into learning and coding with React, and I'm encountering a bug that I need help fixing. The issue lies within my application screen where I have two checkboxes that should function like radio buttons. This means that when on ...

"Discrepancy detected: Image size does not align with table

I recently encountered an issue where I placed an image with a height of 900px inside a table that also had a height of 900px. Strangely, an additional 5px of height was automatically added to the bottom of the table. Here is the code snippet that showca ...

the ajax success function is malfunctioning

I'm encountering an issue with my ajax function. I am trying to change the CSS for certain HTML elements on 'success', using the following code: success:function(d){ $('#name').css('weight','normal'); ...

What is the significance of having a timer in a Redux reducer to prompt a re-rendering process?

Encountered some unusual behavior that I need to understand better Here is the code for my reducer. Strangely, the component linked to the redux state does not re-render with this code. Despite confirming through developer tools that the state updates cor ...

Safari iOS does not properly support responsive images when using srcset and sizes

I am facing an issue with the following code snippet: <img src="/img/footer/logo_white.png?v=2.0" srcset="/img/footer/logo_white.png?v=2.0 1x, /img/footer/logo_white2x.png?v=2.0 2x" > This ...

Tips for creating a dynamic id for the <li> element

I am working on a div that contains UL and LI elements. I want to dynamically generate IDs for these LI elements, instead of using static HTML like this: <li id= "nav-fragment-1"> <li id= "nav-fragment-2"> <li id= "nav-fragment-3"> <l ...

Querying MySQL database for variable values in JavaScript

I have a JavaScript file on my website that carries out calculations. Currently, my variables are defined as global variables in another JavaScript file. What I would like to do is make these variables dynamic by pulling their values from a MySQL database ...

Designing a rounded border radius for various child elements within a layout

I am currently working on creating a circular container that houses an image and a description overlaid at 50% opacity. Here is what I have achieved so far: https://i.stack.imgur.com/pIkO1.png My goal is to apply a uniform border-radius to the entire div ...

A strange issue with ajax: SyntaxError occurs with an unexpected token "if"

Having an issue with my javascript code: function updatePage() { if (request.readyState == 4) if (request.status == 200) var data = JSON.parse(request.responseText); update_select($('select[name=island_name]'), data); ...

Two sets of scrolling bars

Having an issue with my JSFIDDLE parallax effect causing two scrollbars in the result. How can I ensure there is only one scrollbar for all my content? Here is some of the HTML code: <div id="intro"> <p>Sed uelit, sed quia...</p> </ ...

Removing the &nbsp; space character from a webpage using server-side code

I am experiencing difficulties with replacing a blank space in a webform control label. Below is the code for my label: <label id="Lbl1" runat="server">TEXTA&nbsp;&nbsp;TEXTB</label> My goal is to replace the blank spaces in the labe ...