Adjust the number of buttons displayed to the user by changing the value in the HTML input field

I am looking to dynamically adjust the number of buttons available for users to select based on their input value.

My initial thought was to use a JavaScript if...else function to toggle between display: none and display: block depending on the input value, but so far, my attempts have been unsuccessful.

<body>
  <div><input type="text" id="runners" />Select No. of runners</div>
  <br /><br />
  <div id="runner1"><button class="open-button btn1" onclick="openForm()" style="display:block;">1</button></div>
  <div id="runner2"><button class="open-button btn2" onclick="openForm()" style="display:block;">2</button></div>
  <div id="runner3"><button class="open-button btn3" onclick="openForm()" style="display:block;">3</button></div>
  <div id="runner4"><button class="open-button btn4" onclick="openForm()" style="display:block;">4</button></div>
  <div id="runner5"><button class="open-button btn5" onclick="openForm()" style="display:block;">5</button></div>
  <div id="runner6"><button class="open-button btn6" onclick="openForm()" style="display:block;">6</button></div>
  <div id="runner7"><button class="open-button btn7" onclick="openForm()" style="display:block;">7</button></div>
  <div id="runner8"><button class="open-button btn8" onclick="openForm()" style="display:block;">8</button></div>
  <div id="runner9"><button class="open-button btn9" onclick="openForm()" style="display:block;">9</button></div>
  <div id="runner10"><button class="open-button btn10" onclick="openForm()" style="display:block;">10</button></div>
</body>

If the user inputs "6" as the number of runners, only six buttons should be visible.

Answer №1

Here is a solution:

function displayRunners(element) {
  let runnersWrapper = document.querySelector('#runners');
  runnersWrapper.innerHTML = '';
  for (let i = 1; i < Math.min(Number(element.value) + 1, Number(element.max) + 1); i++) {
    let button = document.createElement('button');
    button.id = 'runner-' + i;
    button.innerText = i;
    button.setAttribute('onclick', "showForm(this.innerText)");
    runnersWrapper.appendChild(button);
  }
}

function showForm(index) {
  console.log('The form was opened from runner: ' + index);
}

displayRunners(document.querySelector('#runControl'));
#runners {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
<input id="runControl"
       type="number"
       value="5" 
       min="0" 
       max="10"
       oninput="displayRunners(event.target)">
<hr>
<div id="runners"></div>

You could simply style them using CSS instead of adding unnecessary <div> elements.

Answer №2

  1. Store the input box value in a variable, for example, val.

  2. Capture each number from the 10 buttons and assign them to a variable, let's call it runners.

  3. Utilize parseInt() to convert the string numbers retrieved into integers for both variables val and runners.

  4. Compare the integer values of each number within the runners variable with the parsed value of val and adjust the css display property accordingly based on the comparison result.

Note: Avoid using inline on-* handlers (onclick, oninput, etc.) and opt for event listeners instead.


Refer to the following Code Snippet for a practical demonstration of the steps described above:

// JavaScript 
var btn = document.getElementById("btn");
var val = document.getElementById("runners");

function toggleRunners() {
    var runners = document.querySelectorAll('div[id*="runner"]'); // 'div[id*="runner"]' selects all div elements with an "id" containing "runner"
    
    runners.forEach(runner => {
        var value = parseInt(val.value);
        var run = parseInt(runner.innerText);
        if (run === value || run < value) {
            runner.style.display = "block";
        } else {
            runner.style.display = "none";
        }
    })
}
btn.addEventListener("click", toggleRunners);
<!-- HTML --> <div> <input type="text" id="runners">Select No. of runners <hr /> <button id="btn">Click Me</button> </div> <hr /> <div id="runner1"><button class="open-button btn1" style="display:block;">1</button></div> <div id="runner2"><button class="open-button btn2" style="display:block;">2</button></div> <div id="runner3"><button class="open-button btn3" style="display:block;">3</button></div> <div id="runner4"><button class="open-button btn4" style="display:block;">4</button></div> <div id="runner5"><button class="open-button btn5" style="display:block;">5</button></div> <div id="runner6"><button class="open-button btn6" style="display:block;">6</button></div> <div id="runner7"><button class="open-button btn7" style="display:block;">7</button></div> <div id="runner8"><button class="open-button btn8" style="display:block;">8</button></div> <div id="runner9"><button class="open-button btn9" style="display:block;">9</button></div> <div id="runner10"><button class="open-button btn10" style="display:block;">10</button></div>

Answer №3

Make sure to include this input function:

<input type="text" id="runners" oninput="checkNumber(this.value)"/>

followed by the script below in your code Simple and effective

function checkNumber(val){
      var elements = document.getElementsByClassName("open-button");
      for(var i = 0; i < elements.length; i++){
        elements[i].style.display = "block";
      }
      if (val != null) {
        while (val < 10) {
          val++;
          var class_name = '.btn' + val;
          if (document.querySelector(class_name) !== null) {
            document.querySelector(class_name).style.display = 'none';
          }
        }
      }
    }
  function openForm() {
    console.log('openForm() was called');
  }
<body>
  <div><input type="text" id="runners" oninput="checkNumber(this.value)"/>Select No. of runners</div>
  <br /><br />
  <div id="runner1"><button class="open-button btn1" onclick="openForm()" style="display:block;">1</button></div>
  <div id="runner2"><button class="open-button btn2" onclick="openForm()" style="display:block;">2</button></div>
  <div id="runner3"><button class="open-button btn3" onclick="openForm()" style="display:block;">3</button></div>
  <div id="runner4"><button class="open-button btn4" onclick="openForm()" style="display:block;">4</button></div>
  <div id="runner5"><button class="open-button btn5" onclick="openForm()" style="display:block;">5</button></div>
  <div id="runner6"><button class="open-button btn6" onclick="openForm()" style="display:block;">6</button></div>
  <div id="runner7"><button class="open-button btn7" onclick="openForm()" style="display:block;">7</button></div>
  <div id="runner8"><button class="open-button btn8" onclick="openForm()" style="display:block;">8</button></div>
  <div id="runner9"><button class="open-button btn9" onclick="openForm()" style="display:block;">9</button></div>
  <div id="runner10"><button class="open-button btn10" onclick="openForm()" style="display:block;">10</button></div>
</body>

Answer №4

To achieve this manually, you can follow a similar approach as shown below:

if (#player1) {
    then player2,3,4,5,6... will be hidden
}

if (#player2) {
    then player3,4,5,6... will be hidden
}

This is the basic logic for implementing this function using JavaScript.

Answer №5

Take a look at this cool implementation using jQuery: https://jsfiddle.net/emeka247/x5sk2gh8/4/ the html

<div>
   <input type="text" id="runners">Select No. of runners
</div>
<br><br>
<div id="runner1">
   <button class="open-button btn1" onclick="openForm()" style="display:none;">1</button>
</div>
<div id="runner2">
   <button class="open-button btn2" onclick="openForm()" style="display:none;">2</button>
</div>
<div id="runner3">
   <button class="open-button btn3" onclick="openForm()" style="display:none;">3</button>
</div>
<div id="runner4">
   <button class="open-button btn4" onclick="openForm()" style="display:none;">4</button>
</div>
<div id="runner5">
   <button class="open-button btn5" onclick="openForm()" style="display:none;">5</button>
</div>
<div id="runner6">
   <button class="open-button btn6" onclick="openForm()" style="display:none;">6</button>
</div>
<div id="runner7">
   <button class="open-button btn7" onclick="openForm()" style="display:none;">7</button>
</div>
<div id="runner8">
   <button class="open-button btn8" onclick="openForm()" style="display:none;">8</button>
</div>
<div id="runner9">
   <button class="open-button btn9" onclick="openForm()" style="display:none;">9</button>
</div>
<div id="runner10">
   <button class="open-button btn10" onclick="openForm()" style="display:none;">10</button>
</div>

Here is the jQuery code:

$(document).ready(function(){
$(document).on('keyup','#runners',function(){
$input=$('#runners').val();
if($input==1){
$('.btn1').css('display','block');
$('.btn2,.btn3, .bt4, .btn5, .btn6, .btn7').css('display','none');
}else if($input==2){
$('.btn1, .btn2').css('display','block');
$('.btn3, .btn4, .btn5, .btn6, .btn7').css('display','none');
}else if($input==3){
$('.btn1, .btn2, .btn3').css('display','block');
$('.btn4, .btn5, .btn6, .btn7').css('display','none');
}else if($input==4){
$('.btn1, .btn2, .btn3, .btn4').css('display','block');
$('.btn5, .btn6, .btn7').css('display','none');
}else if($input==5){
$('.btn1, .btn2, .btn3, .btn4, .btn5').css('display','block');
$( '.btn6, .btn7').css('display','none');
}else if($input==6){
$('.btn1, .btn2, .btn3, .btn4, .btn5, .btn6').css('display','block');
$(' .btn7').css('display','none');
}
});
});

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

How can I extract particular combinations from a PHP array?

I have a unique question that is quite specific and despite searching online, I couldn't find an answer. So, I decided to seek advice here. Imagine my webpage has three sliders: one for selecting color options for a square, another for a circle, and ...

Using the SmartSheets API to Iterate Over a List to Determine the Variable of a Function

I have a group of numerical values listed below that are stored in a variable. [700000000084, 100000000051652, 8800000000000072, 280000000000004, 680000000000008, 880000000000006] My goal is to iterate through this list using the SmartSheets API to gathe ...

The CSS styles are not applied when using self.render("example.html") in Tornado/Python

I'm still learning Python and programming in general. I'm currently using Tornado as my web server to host my websites. However, when I try to generate a dynamic html page using self.render("example.html", variables here), the resulting page does ...

PHP Incrementing a Number without Defined Limit

I am facing an issue with the code provided below as it is throwing back an 'undefined' error for the countingNumbers variable. My objective is to incorporate the class name 'numbered' so that I can iterate over it in JavaScript and ass ...

Creating a Visual Balance with CSS Image Margins

div#columncontents { background: black; } img.colimg03 { position: relative; right: -70px; } img.colimg02 { position: relative; right: -40px; } <div id="columncontents"> <div class="columnimage"> <img class="colimg01" src=" ...

How to use JavaScript to validate if an input field is empty in IE

I am facing an issue with the required attribute in IE9. While the attribute works fine in IE10 and above, I am struggling to get it to function in IE9. I have attempted the following: $('#submit-button').click(function(){ if($('#message ...

Executing the onSuccess callback in Ajax without any ability to manipulate the ajax requests

My dilemma lies in needing to execute a JavaScript function upon the successful completion of an AJAX call. Unfortunately, I am unable to directly manage the AJAX calls as they are handled by the DNN5 framework. Is there a way for me to trigger my functio ...

retrieve the position of a descendant element in relation to its ancestor element

I'm encountering a challenge while attempting to solve this issue. I have elements representing a child, parent, and grandparent. My goal is to determine the offset position of the child (positioned absolutely) in relation to the grandparent. However, ...

Customizing the CSS for individual posts in WordPress based on their post

I am interested in establishing a unique look for each individual post on my wordpress.org blog. Is there a way to customize the CSS code of individual posts without changing the design of other posts? I have tried using categories to create a new PHP fi ...

Angularjs regex filter: applying regular expressions to filter data

I've created a regex pattern to match URLs like this: /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/ Now, I need to incorporate this regex into a filter that will specifically extra ...

Thymeleaf not triggering JQuery click event

Currently working on a Spring Boot site where I have a list of elements, each containing a link. The goal is to trigger a javascript function when these links are clicked. <div class="col-sm-4" th:each="product : ${productsList}"> <!-- Code... ...

Angular - Triggering actions with ng-hide and ng-show events

Is there a better solution for monitoring hide and show expressions across all elements in my app? I am aware that I can achieve this by wrapping the show directive with a function that simply returns the argument: <div ng-show="catchShow(myShowExpr = ...

Unexpected issue with accessing the jQuery class descendant

I am currently developing a photo gallery and I am trying to add some CSS styling to the first photo that is visible within my #wrapper div. Below is the code snippet I have been working on: $('.inside:first-of-type>div:nth-of-type(1)').css(& ...

Guide to displaying an HTML input box when the option 'other' is chosen using PHP

I am currently trying to find a way to display an HTML input field when the "other" option is selected from a dropdown menu. The options in the dropdown list are populated by a MySQL database query, which is functioning correctly. However, I am strugglin ...

Angular beautiful URLs are not functioning

I recently developed a SPA angularJS application that was working perfectly fine with normal routing using hashes (e.g. somesite.com#/something). However, I became tired of the hash routing and discovered something called "pretty urls" with $locationProvid ...

The three.js object is not displaying its shadow as expected

I am relatively new to Three JS and encountering some difficulties with my code. The main issue I'm facing is the inability to achieve proper shadows for all the objects I've integrated. You can see the problem in the following image: https://i. ...

Troubleshooting Problem with CSS Display in Spring Security 3.2

After deciding to integrate 'Spring security 3.2.0' into my current web application, which was originally developed without Spring and utilizes Primefaces & EJB 3, I encountered a challenge. Upon starting the basic configurations, I noticed that ...

Make sure to properly check the size of the image before uploading it in express js

Below is the code I have written to verify if an image's size and width meet the specified criteria: im.identify(req.files.image,function (err,features) { //console.log(features); if(features.width<1000 ...

The necessary data is missing in the scope of the callback function

I'm facing an issue with a callback function's variable losing its scope. Consider the following simplified array of two objects: const search = [{socket: new WebSocket('ws://live.trade/123')}, {socket: new WebSocket( ...

What causes the error "Failed to load SWC binary for win32/x64" when using getStaticProps?

Encountering an issue while using getStaticProps() in a Next.js application, resulting in the following error when running the app: warn - Attempted to load @next/swc-win32-x64-gnu, but it was not installed warn - Attempted to load @next/swc-win32-x64-ms ...