Using buttons as spinners for input elements with identical styles but unique identifiers

Currently, I am in the process of developing a project that involves users. In order to display all users, I am executing a query on an SQL database. After styling the interface, I have added an input element beside each user, which initializes at zero. Additionally, there are two buttons - one for incrementing (#up) and another for decrementing (#down) the value displayed in the input element. Essentially, these buttons act as spinners. Moreover, I aim to set limits for the input element, with a minimum value of 5 and a maximum of 500.

Despite my attempts at implementing various 'onclick' functions, I have not been successful. While using 'GetElementById', it only alters the value of the input element for the first user due to the unique ID assigned to it. How can I rectify this issue?

I deeply appreciate any assistance provided. As a beginner, I welcome corrections if I have made any mistakes rather than receiving downvotes.

Below is the HTML code:

 <span class='username'>" . $row['username'] . "</span>
<form name='matchcreator' id='amount' action='arena.php' method='post'>
<input name='m-maker' type='text' id='price' maxlength='15' value='0'/>
<button id='up' type='button'><img src='images/up.png' width='10px' height='10px' href='#'></button>
<button id='down' type='button'><img src='images/down.png' width='10px' height='10px' href='#'></button>
</form>

Answer №1

You have two options to customize the input controls: either follow David Cash's advice and utilize the HTML5 input element with spinners, or you can opt to eliminate the IDs from the up/down arrows and the input element itself. Here is an example of what that might look like:

Customized HTML

    <span class='username'>".$row['username']."</span>
    <form name='matchcreator' id='amount' action='arena.php' method='post'>
        <input name='m-maker' type='text' class='price' maxlength='15' value='0'/>
        <button class='up' type='button'><img src='images/up.png' width='10px' height='10px' href='#'></button>
        <button class='down' type='button'><img src='images/down.png' width='10px' height='10px' href='#'></button>
    </form>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script>
    $(function () {
    $(".up").on("click", function () {
        var trigger = $(this);
        var input = trigger.prev();
        if (Number(input.val()) < 500) {
            input.val(Number(input.val()) + 1);
        }
        else { alert("max value reached"); }
    }); 
    $(".down").on("click", function () {
        var trigger = $(this);
        var input = trigger.prev().prev();
        if (Number(input.val()) > 5) {
            input.val(Number(input.val()) - 1);
        }
        else { alert("min value reached"); }
    });
    }
</script>

Answer №2

Why not give simple HTML 5 a try for your input box?

<input name ="m-maker" name="price" type="number" min="1" max="500" value="5">

By using this code, you can easily create an input box with spinners without the need for additional buttons to adjust the value.

Check out this example on Plunker

Answer №3

Here is a demonstration of the requested functionality using classes instead of IDs:

<form name='matchcreator' class='amount' action='arena.php' method ='post'>
    <input  name='m-maker' type='text' class='price' maxlength='15' value='0'/>
    <button class='up' type='button'><img src='images/up.png' width='10px' height='10px' href='#'></button>
    <button class='down' type='button' '><img src='images/down.png' width='10px' height='10px' href='#'></button>
</form>

Sample usage of jQuery:

$(".down").on("click", function() {
    var input = $(this).prev(".price");
    input.val(parseInt(input.val()) - 1);
});

$(".up").on("click", function() {
    var input = $(this).prev(".price");
    input.val(parseInt(input.val()) + 1);
});

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

Tips for implementing both an onChange and onSubmit event for a MUI TextField

I'm currently working with React and MUI and have created a form like the following: const handleUserInput = (event) => { set_user_input(event) } const handleSubmitForm = () => { if (user_input == 'help'){ ...

Tips for implementing filters in Angular2 without using the package field in the console

I am currently experiencing an issue with a filter field in my code. The filter works fine when all the package data is present, however, some items do not have a package field. As a result, I need to filter based on the package name but I am encountering ...

Strategies for positioning identical Highcharts series next to one another

I am currently utilizing highcharts to create column charts. My column chart consists of multiple series, structured like this: Here is the code I am working with: $(function () { var chart; $(document).ready(function() { ...

Switch the view to a grid layout upon clicking

Using bootstrap 5, I've successfully created a list view: <div class="col"> Click to switch to grid/list </div> Below is the content list: <div class="row mt-3 list"> list view ... ..... ....... </div ...

Using Google Chart API to create stacked bar charts with annotations using symbols

I am trying to annotate the bars in my stacked bar chart with currency symbols for profit and costs. While I have been able to successfully annotate the bars without currency symbols, I am facing difficulties in displaying them with the $ prefix. Can anyo ...

Generating dynamic @returns annotations in JSDoc based on the value of @param

How can I properly document the function in order for vscode-intellisense to recognize that getObject("player") returns a Player type and getObject("bullet") returns a Bullet type? /** * @param {string} type * @return {????} */ function getObject(type ...

Retrieve a div element using Ajax from the result of an If statement

I need to extract a specific div from the data returned by an if statement that is formatted as HTML, and then display it within another div. I have been attempting to achieve this using the code below, but so far it has not been successful... Here is my ...

Supply a variety of values to jQuery

Recently, I created a loop to retrieve multiple rows from the database. Each row includes a link and a hidden input with a value of posting_id. Essentially, this functions similarly to a "like" button on Facebook. The hidden input stores the posting_id, wh ...

Steps to customize a CSS file within node_modules

Is there a way to make changes to a CSS file in the "node_modules" dependency without them being overwritten when I run npm install? I want to keep the modifications I've made to the node module files. ...

Transferring items between different containers without using innerHTML

I've got an embedded <ul> within a (hidden) <aside id="idDetails">. How can I move the ul element from inside the aside and position it in a <div id="projectSide"> without using innerHTML? Any solutions in both plain JavaScript and j ...

What is the method for displaying a div adjacent to a password input field?

I am attempting to display a password verification box next to an input field. The current logic is functioning properly, but the box containing all password requirements is not appearing in the correct position. Instead of being positioned adjacent to the ...

Using an xmlhttprequest to retrieve a PDF file functions properly in synchronous mode, but encounters issues in

Today I'm experimenting with some code that scrapes PDFs from a chrome extension by detecting user-clicked links. I've noticed that synchronous xmlhttprequests work perfectly for both HTML documents and PDFs. However, I seem to be facing an issue ...

VueJS component fails to remain anchored at the bottom of the page while scrolling

I am currently using a <md-progress-bar> component in my VueJS application, and I am trying to make it stay fixed at the bottom of the screen when I scroll. I have attempted to use the styles position: fixed;, absolute, and relative, but none of them ...

Insert a gap between the two columns to create some breathing room

Does anyone know how to create spacing between columns in an HTML table without affecting the rows? In my table, each column has a border around it: <table> <tr> <td style="padding:0 15px 0 15px;">hello</td> <td style=" ...

Error message: Angular 7 - Running out of memory due to JavaScript heap

When attempting to run the ng serve command in my Angular 7 application, I encountered an error message stating "JavaScript heap out of memory." After researching various responses on Stack Overflow, it became clear that this issue stems from inadequate m ...

Tips for postponing the first button event in Vue 3 and JavaScript

My current task involves setting up a button event in Vue 3 that triggers a setTimeout countdown on the button before redirecting to another page. The event function has a conditional statement that initiates a countdown from 5 to 0 as long as the countVal ...

Preventing memory leaks by harnessing the power of Node Streams and promises

I am trying to wrap node streams in an async function, but I'm concerned about potential memory leaks in the following code. Will readStream and result be properly garbage collected after the promise is resolved or rejected? If not, what steps can I t ...

Exploring the Jquery functionality: $(document).ready(callback);

Hey there, I'm struggling to run a function both on window resize and document ready. The issue is that when the resize event is triggered by mobile scroll, it's essential to ensure the height hasn't changed. Oddly enough, the code works fin ...

Display a specific value from a dropdown using jQuery

I have a code snippet that effectively selects specific elements when the "get icon" button is clicked, displaying the correct option value. The challenge I'm facing is figuring out how to display the selected option value upon selecting an item from ...

Create a Jest unit test for a specific function

I started my first unit test in react with jest this afternoon. The initial 5 tests I need to do involve testing the return functions, which isn't too difficult. However, I'm struggling to understand how to perform unit testing on my login funct ...