A window interface in Javascript that allows for dynamic arrays and multiple choice answers

I've been working with multiple arrays and encountered a problem. Adding additional questions is not an issue when there's only one question div generated. However, if I add another question div, I can't add more questions to either of the windows (the same applies to any number), and the error message I receive is that newdiv[counterq] is undefined. Can anyone assist me with this problem? Thank you!

Additionally, how can I move the AddOption div below the newly created option input?

I'm new to programming, so I apologize if my explanations are not using correct terms. Thank you!

Edit: Updated with a new problem. Didn't want to create a separate topic.

HTML:

var counterq = 0;
var limitq = 3;
var countero = 0;
var limito = 5;

function AddContent(divName) {
    countero = 0;
  if (counterq == limitq) {
    alert("You have reached the limit of adding " + counterq + " inputs");
  } else {
    var newdiv = new Array()
    newdiv[counterq] = document.createElement('div');
    newdiv[counterq].className = "ContentWindow[" + counterq + "]";   
    newdiv[counterq].innerHTML = "<p class='ContentQuestion'>Question " + (counterq + 1) + " </p> <input type='text' class='AddQuestionInput' value='Type your question' name='myQuestion[" + counterq + "]'>"; 
    if (countero == limito) {
      alert("You have reached the limit of adding " + countero + " options");
    } else {
        newdiv[counterq].innerHTML += "<div class='OptionInputOuterWindow'><span class='OptionInputDescription'>Option " + (countero + 1) + "</span> <input type='text' class='AddOptionInput' name='myQuestion[" + counterq + "]"+"[myInputs]"+"[" + countero + "]'></div>";
        newdiv[counterq].innerHTML += "<div class='OptionInputOuterWindow'><span class='OptionInputDescription'>Option " + (countero + 2) + "</span> <input type='text' class='AddOptionInput' name='myQuestion[" + counterq + "]"+"[myInputs]"+"[" + (countero+1) + "]'></div>";
        document.getElementById(divName).appendChild(newdiv[counterq]);
        countero += 2;
         AddOption = function() {
            var counterq = 0;
            var limito = 5;
            if (countero == limito) {
                alert("You have reached the limit of adding " + countero + " options");
            } else {
                newdiv[counterq].innerHTML += "<div class='OptionInputOuterWindow'><span class='OptionInputDescription'>Option " + (countero + 1) + "</span> <input type='text' class='AddOptionInput' name='myQuestion[" + counterq + "]"+"[myInputs]"+"[" + countero + "]'></div>";
                $("div[class*=ContentWindow]").css("height", "+=27");
                countero++;
            }
        };
    }
        $(".container").css("height", "+=344");
        newdiv[counterq].innerHTML += "<div class='AddOption' onclick='AddOption();'><img src='/img/Plussmall.png'>Add option</div>";
    counterq++;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <div id="Content"></div>


        <div class="AddContent" onclick="AddContent('Content');" >
        <img src="/img/Plussmall.png">Add content
        </div>

Answer №1

To increase the counter by 2, use countero += 2 instead of countero++.

var counterq = 0;
var limitq = 3;
var countero = 0;
var limito = 5;

function AddContent(divName) {
  if (counterq == limitq) {
    alert("You have reached the limit of adding " + counterq + " inputs");
  } else {
    var newdiv = new Array()
    newdiv[counterq] = document.createElement('div');
    newdiv[counterq].className = 'new-rect';
    if (counterq == limito) {
      alert("You have reached the limit of adding " + countero + " options");
    } else {
      newdiv[counterq].innerHTML = "Entry " + (countero + 1) + "<br><input type='text' name='myInputs[" + countero + "]'><br>Entry " + (countero + 2) + "<br><input type='text' name='myInputs[" + countero + "]'><br>";
      document.getElementById(divName).appendChild(newdiv[counterq]);
      countero += 2;
    }
    
    counterq++;
  }
}
.new-rect {
  width: 300px;
  height: 100px;
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Content"></div>

<input type="button" class="AddContent" value="Add content" onclick="AddContent('Content');">

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

Timeout error occurred in Async.js because the callback was already triggered

Whenever I execute index.js, I encounter an ETIMEDOUT or ECONNRESET error followed by a Callback was already called error. Initially, my assumption was that the issue stemmed from not including a return before calling the onEachLimitItem callback. Consequ ...

Displaying and hiding elements as the page is scrolled

Is there a way to create a single scrolling page with a fixed element that remains visible as the user scrolls down? Imagine an image of a car on a road, where the car appears to be moving down the road as the user scrolls. The car should go under certain ...

Setting an error state on the parent div of a checkbox

I am facing an issue with styling a standard HTML checkbox when it is in an error state. Since it's not possible to style the checkbox directly, I am attempting to apply the styling to its parent div instead. Consider this example: <div class="fo ...

Having trouble retrieving text from the data attribute

I have a Bootstrap Table with an edit button on each row. I've implemented a data formatter to include the record ID as a data attribute that should be accessible when the button is clicked. Oddly, while inspecting the element in the console shows tha ...

Emphasize the content within the table cell

Currently, I am working with an HTML table that is being generated by Java. My goal is to highlight the text within a table cell without changing the background color of the entire cell. I should mention that I am aware of the option to achieve this by ma ...

Modifying data-* attributes with jQuery through contenteditable

I am currently developing basic rich text editing functionality for a client by utilizing contenteditable. One specific feature involves changing the values of data-* attributes within a button, like this example: <button data-type="telephone">Text&l ...

Equalizing Grid Heights in Twitter Bootstrap

I need to achieve the same height for my sections using Bootstrap 4 but I want only the content <div class="content"> to be enlarged, not the header and footer. section { background: #ccc; border: 1px solid #000 } header { background: red; ...

"Enhance your website with the powerful combination of SweetAlert

I'm having trouble getting my ajax delete function to work with SweetAlert. I can't seem to find the error in my code. Can someone help me figure out how to fix it? function deletei(){ swal({ title: 'Are you sure?', ...

Is it possible to include three sorting states in jQuery DataTables: ASC, DESC, and NO_SORT?

When clicking on a column header in jQuery DataTables, the sorting order toggles between ascending (Down Arrow) and descending (Up Arrow). However, I am looking to customize this behavior: 1st-click ascending 2nd-click descending 3rd-click no-sorting 4th- ...

Unable to locate AngularJS controller

As my single controller started to become too large, I decided to split it into multiple controllers. However, when I try to navigate to /signup, I encounter an issue where my UserController cannot be found. The error message states: Error: [ng:areq] Argu ...

Interact with embedded elements in JavaScript by using the onClick event

Here is a JavaScript code snippet I've been working on: <div> <tr onClick="click1()"> <td> click 1 </td> <td onClick="click2()"> click 2 < ...

Creating a full-height application with CSS3 Flexbox and managing overflow

I'm currently working on an app that utilizes a traditional email layout similar to the one illustrated below. Using the new CSS3 flexbox model, everything was functioning perfectly until I added the feature for users to dynamically insert new items ...

Pug conditional elements not styling with CSS

Currently immersed in the world of Pug, node.js, and express as I build a web application. Facing hurdles when trying to style elements within Pug conditionals using CSS. For instance, consider this Pug snippet: div(id='outside') if authoris ...

Is there a way to efficiently process multipart/formdata, application/json, and text/plain within a single Express handler?

Operating an express demo server that mirrors the client's POST requests back to it is a part of an educational practice. In this exercise, the client makes a POST request using the fetch API, like so: fetch('http://localhost:5000/', { m ...

I created a new game where I can select two images to display, but for some reason, it is only showing one

My rock paper scissors game functions well, except for one issue. I programmed it to display both the player's choice and the bot's choice along with an outcome message (win, tie, or lose). However, I encountered a problem where only the player&a ...

The feature user.presence.status is now operational in discord.js v13

I was trying to get my bot to rename a channel to show the number of users currently online. I wanted to specifically filter out users who are online, idle, or in do-not-disturb mode, as well as offline users. However, the code I wrote doesn't seem to ...

Concealing two out of three div elements inside a specified id container using jQuery

I have encountered an issue with my structure, which looks like this: http://jsfiddle.net/NEFhF/3/ This is how it should work: When I click on the "id contacts", the "field body" and the "field foot" should be hidden. However, the id and the field head b ...

"Troubleshooting a CSS problem with off-canvas layouts

I've created a page with divs that create a parallax effect on scrolling, you can view the demo here. However, I encountered an issue when adding a Foundations off-canvas menu - it prevents me from being able to scroll down. How can I resolve this an ...

Tips for optimizing re-rendering in Redux when a single state changes to avoid unnecessary updates in other components

I recently completed a React project that utilizes Redux for state management. In this project, I have implemented two different states stored in the same reducer and accessed by separate components. However, I've encountered an issue where changing t ...

Executing a PHP function every second using JS/Ajax: A step-by-step guide

Currently, I am utilizing the Highcharts API from http://www.highcharts.com/demo/dynamic-update to create a dynamic graph that reflects server load on my web panel. I have developed a PHP function called get_server_cpu_usage() which retrieves the current ...