How to insert a <br> tag at specific positions in a JavaScript array

I am currently working on developing a JavaScript calculator program.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8>
    <script type="text/javascript>
        var buttons = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "+", "-", "*", "/", "C", "Enter"];
    </script>
</head>
<body>
<script type="text/javascript>
    var n = 0;
    for (var i = 0; i < buttons.length; i++) {
        document.write("<button>" + buttons[i] + "</button>");
        if (i === 3 * n) {
            document.write("<button>" + buttons[i] + "</button><br>");
            n++;
        }
    }
</script>
</body>
</html>

When the output is displayed, it should look something like this:

1 2 3 4

5 6 7 8

9 0 + -

  • / C Enter

However, I am experiencing some issues with my current output:

1 2 4

5 7

8 0

  • *

/ Enter

I am trying to figure out why there are missing buttons such as 3, 6, 9, -, and C. My goal is to create a new line every time the for loop reaches indexes that are multiples of 3 (which means a new line after button 4, 8, etc.).

Answer №1

Embedding dynamic content on a webpage using document.write
isn't the best approach, but setting that aside, your logic is flawed.

I'm looking to create a new line when the for loop reaches every 3*n indexes

What you really need is to insert a <br/> tag after every 4th element in the array

for(var i = 0; i <buttonname.length; i++){
    if(i != 0 && (i%4) == 0)
       document.write("<br>");
    document.write("<button>"+buttonname[i]+"</button>");        
}

var buttonname = ["1","2","3","4","5","6","7","8","9","0","+","-","*","/","C","Enter"];

var n=0;
for(var i = 0; i <buttonname.length; i++){
    if(i != 0 && (i%4) == 0)
       document.write("<br>");
    document.write("<button>"+buttonname[i]+"</button>");
}

Answer №2

Your code block within the if statement seems to be causing issues. Try using the revised if block provided below for a smoother operation:

if( (i+1) %3 == 0)
document.write("<br />");

This particular check ensures that the index is divisible by 3 before inserting a newline. Adding i+1 compensates for the loop starting at 0.

It's crucial to scrutinize your code structure and writing style for better readability. Your current 'code handwriting' might need improvement.

View SSenter image description here

If you're looking for a helpful JavaScript array tutorial, check out this resource with nicely formatted code examples.

Answer №3

Have you considered utilizing the modulo operation?

var buttonnames = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "+", "-", "*", "/", "C", "Enter"];

for (var j = 0; j < buttonnames.length; j++) {
    document.write("<button>" + buttonnames[j] + "</button>");
    if (j % 4 == 3) {
        document.write("<br>");
    }
}

Check out the JSFIDDLE link for more information.

Answer №4

Here is the solution to your query:

<!DOCTYPE html>
 <html>

<head>
<meta charset="UTF-8">
 <script type="text/javascript>
var buttons = ["1","2","3","4","5","6","7","8","9","0","+","-","*","/","C","Enter"];
</script>
</head>
<body>
<script type="text/javascript>
var num=0;
for(var j = 0; j <buttons.length; j++){
document.write("<button>"+buttons[j]+"</button>");
if(j!=0 && (j+1)%3==0)
  document.write("<br>");
}
</script>

</body>
</html>

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

Editing Fields in Asp-net 3.1: A guide to using Summernote or other rich text editors

I am facing an issue where some fields in my database contain strings that generate HTML code such as "<p'>Hello world</p'>". I am attempting to import these strings into a summernote rich text editor for editing purposes. H ...

In PHP, you can transform an associative array with two keys, "snf" and "rate", into an array where each "snf

Below is an example of an associative array: Array ( [0] => Array ( [Snf] => 2.000 [Rate] => 0.000 ) [1] => Array ( [Snf] => 2.000 [Rate] => 0.000 ) ...

clicking on internal links in the bootstrap side menu causes it to jump

Im trying to add a side menu to a help page. The menu and internal links are functioning properly, but when clicked, the side menu partially goes behind the navbar. As a beginner, I'm not sure how to resolve this issue. Can someone offer some guidan ...

The AJAX request encountered an unexpected failure that cannot be identified (Using jQuery)

Are you facing issues with a service that returns JSON data? Check out this URL: If you're attempting a simple AJAX request, here's some sample code to get you started: $.ajax({ type: "get", url: "http://api.drag2droid.shamanland.com/ca ...

Nodejs is encountering difficulties in transmitting precise error messages to the browser

I am encountering an issue in my nodejs application with error handling. Despite setting up specific error messages, the browser receives a generic error object instead. The error messages are only visible in the nodejs console and not on the browser which ...

What steps are involved in integrating OpenCV into a JavaScript project?

After recently installing OpenCV via npm using this guide: https://www.npmjs.com/package/opencv I'm facing a simple question. How can I actually utilize the OpenCV library in my project? The site provides a face detection example code snippet: cv.r ...

How can I display two slides at once in Ionic 2/3 on a wide screen?

I have been searching for a solution that will allow me to display 1 ion-slide if the device screen is small, but if it's larger, then I want to display 2 ion-slides. Unfortunately, I have not been able to find a suitable solution yet. As an example, ...

Having trouble retrieving the second parent of my input element using jQuery

Within my web application, there exists a particular input element. I am aiming to alter the text within the span below from "-" to a different value. Here is the current markup: <span dir="none"> <table id="OrderQuickOrder_a91a0ce2-7fb6-4c9 ...

Issue: A problem has arisen with the element type, as it was supposed to be a string for built-in components but is currently undefined. This error is being encountered

Help needed: Error in my code! I am working with three files: HeaderOption.js, HeaderOptions.js, Search.js This is the content of HeaderOptions.js import HeaderOption from "./HeaderOption"; import DotsVerticalIcon from "@heroicons/react/o ...

Disallowing selection on input text field

I am seeking to disable selection on an input field while still allowing for focusing, with the following criteria: Preventing selection via mouse Preventing selection via keyboard (including Ctrl+A, shift+arrows) Permitting focus on the field using both ...

Converting an unordered list into a <select> dropdown with jquery - a step-by-step guide

Can you help me transform an unordered list that looks like this? <ul class="selectdropdown"> <li><a href="one.html" target="_blank">one</a></li> <li><a href="two.html" target="_blank">two</a></ ...

Ways to dynamically implement a JSON configuration file in React JS during runtime

Looking to achieve text and image externalization in React? It's all about making changes in a JSON file that will reflect on your live Single Page Application (SPA). Here's an example of what the JSON file might look like: { "signup. ...

Traverse through a list utilizing a jQuery carousel animation

I am attempting to create a looped list with a carousel effect. It seems like the script should first determine the total number of items in the list in order to perform calculations. Then, it can execute an action such as this: Adding an item on one sid ...

Trying to locate the biggest value within an array is causing some issues

Create a program that takes a series of integers as input, stores them in an array, and then sorts the integers by using a function called selection_sort. The selection_sort function should perform the following actions when given an array with n elements: ...

Posts created in Express using the node-postgres module are not being retrieved by queries in async routes

Running a basic query from an express route seems to be causing some issues for me: var router = require('express-promise-router')() const { Pool } = require('pg') const pool = new Pool({ user: 'user', password: 'pa ...

Discover the magic of v-model in Vue 3 Composition API

Can someone help with managing reactivity in form fields using Vue3 Composition API? I'm having trouble getting my code to work correctly. When I type text into the input field, Vue devtools does not show any changes in the ref data. Here's a sim ...

Transferring string to model in Swift 3

Having trouble with my PhotoModel's eventDate() method... I've initialized it like this: let newPhotos = PhotosModel() // Creating an instance newPhotos.eventDate = item.event_date! // Setting the parameter Within the didSelectItemAt method, ...

Retrieve the property by mapping the click event

I am looking for a way to retrieve the ID of a specific item when a link button inside a mapped list is clicked. How can I achieve this functionality? idFinder(){ console.log('ID:', item.id); } this.sampleData = this.state.data.map((item, ...

Storybook/vue causing issues with aliases not functioning as intended

I'm currently utilizing Storybook for Vue and I am endeavoring to integrate aliases into the webpack config within storybook/main.js: resolve: { alias: { 'vue$': 'vue/dist/vue.esm.js', '@': path.resolve ...

How can we utilize the Next.js pages router to efficiently import code that should be executed on the client side?

I am incorporating Google Maps into my project using the @googlemaps/extended-component-library library. You can find more information about this library here. import '@googlemaps/extended-component-library/api_loader.js'; import '@googl ...