Home > Software design >  html Div with javascript numerical widgets
html Div with javascript numerical widgets

Time:05-01

what I want to achieve

I want to create It dynamically by providing n n=total number for example in above image n=30

I want to make it in html, using jquery or javascript and its not a keypad moreof a counter of how many questions are inserte and how many left.

CodePudding user response:

Using CSS grid:

const widgetContainer = document.getElementById("widget-container");

let n = 30;

for (i = 1; i <= n; i  ) {
    widgetContainer.innerHTML  = "<button>"   i   "</button>";
}
div#widget-container {
    display: grid;
    grid-template-columns: repeat(6, calc(100%/6));
    grid-gap: 5px;
    max-width: 250px;
}

div#widget-container>* {
    display: flex;
    justify-content: center;
    border: 1px solid black;
    align-items: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="widget-container">
    </div>
</body>
</html>

CodePudding user response:

This is pretty simple to do with CSS Grid, and some JavaScript.

Create a function that accepts a number, and loops until that number creating an HTML string on each iteration. It places each string into an array, and then returns the joined array as a string of HTML.

That HTML string is added to a container that uses Grid to display the HTML.

Since this isn't a keypad you can add a supplementary data attribute to each element so you can target them separately if you need to.

function createButtons(n) {

  // Create an array
  const html = [];

  // Push HTML into the array on each iteration
  // Each button has its own data id
  // Note: I've used a button here because they're
  // easier to style
  for (let i = 1; i <= n; i  ) {
    html.push(`<button data-id="${i}"  disabled>${i}</button>`);
  }

  // Return the joined-up array as a string
  return html.join('');

}

// Select the container, and add the result
// of calling the function as its innerHTML
const grid = document.querySelector('.grid');
grid.innerHTML = createButtons(30);

// Set the count, and grab all the buttons
const count = 7;
const buttons = document.querySelectorAll('.pad');

// Now you can loop over the button collection, and
// add an active class to each button in the loop...
for (let i = 0; i < count; i  ) {
  buttons[i].classList.add('active');
}

//...or activate them seperately
const eighteen = document.querySelector('.pad[data-id="18"]');
eighteen.classList.add('active');
.grid { display: grid; width: 250px; grid-template-columns: repeat(5, 1fr); row-gap: 0.6em;}
.pad { padding: 0.5em 0.2em; border-radius: 5px; color: red; border: 1px solid red; background-color: white; width: 40px;}
.active { background-color: lightblue; color: black; }
<div ></div>

  • Related