What is the best way to implement an input spinner with changing values?

Seeking assistance in creating an input spinner with dynamic values (e.g. 125, 180, 200, 270, 260, etc.) stored in a database using Laravel, JavaScript, HTML, CSS, and Bootstrap.

I managed to display the values in a dropdown but struggling to integrate them into an input spinner.

<select class="form-select form-select-lg srd" onchange="facebookrr()" id="facebookpack" aria-label="Default select example">

     <option selected value="">Select package</option>
      @foreach ($facebook as $item)
        <option value="{{ $item->amount }}">{{ $item->amount }}</option>
     @endforeach
</select>

Utilizing Bootstrap's input spinner component.

<input type="number" value="5" min="0" max="100" step="1">
<script>
   $("input[type='number']").inputSpinner();
</script>

Any guidance on resolving this issue would be greatly appreciated!

Answer №1

Could you provide more context? Are you interested in creating individual input spinners for each value to allow users to modify dynamic values, or do you want the spinner to simply switch between those values?

If you choose the first option, you can easily set the value attribute of the input element similar to how you did with the option elements.

@foreach ($facebook as $item)
    <input type="number" value="{{ $item->amount }}" step="1" min="0" max="1000" />
@endforeach
<script>
    $("input[type='number']").inputSpinner();
</script>

For the second option, you might need to utilize JavaScript. Essentially, you would create an array of desired values and keep track of the index containing the current value of the input element. Here's a basic example:

// Generate the array using your Laravel code.
const vals = [];
@foreach ($facebook as $item)
    vals.push("{{ $item->amount }}");
@endforeach

let oldIndex = 1;
$("input[type='number']").inputSpinner()

$('#myInput').on('input', function() {
    let goalValue = $(this).val();
    let newIndex = oldIndex;

    if(goalValue > vals[oldIndex]) {
        newIndex++;

        if(newIndex >= vals.length) newIndex = vals.length - 1;
    } else if(goalValue < vals[oldIndex]) {
        newIndex--;

        if(newIndex < 0) newIndex = 0;
    }

    oldIndex = newIndex;
    $(this).val(vals[newIndex]);
});

Here is a snippet of the complete code with HTML included

<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9bbb6b6adaaadabb8a9f4b0b7a9acadf4aaa9b0b7b7bcab99eaf7eaf7ea">[email protected]</a>/src/bootstrap-input-spinner.min.js"></script>
  </head>
  <body>
    <input type="number" step="1" min="0" max="1000" id="myInput" value="1" />  
    <script>
      const vals = ['125', '180', '200', '260', '270']; // ensure numbers are in ascending order
      let oldIndex = 0;
      
      $("input[type='number']").inputSpinner()
      
      $('#myInput').on('input', function() {
        let goalValue = $(this).val();
        let newIndex = oldIndex;
        
        if(goalValue > vals[oldIndex]) {
          newIndex++;
          
          if(newIndex >= vals.length) newIndex = vals.length - 1;
        } else if(goalValue < vals[oldIndex]) {
          newIndex--;
          
          if(newIndex < 0) newIndex = 0;  
        }
        
        oldIndex = newIndex;
        $(this).val(vals[newIndex]);
      });
    </script>   
  </body>
</html>

For further assistance with bootstrap input spinners, visit .

UPDATE SUMMARY: Credit to mplungjan for prompting me to test the code, leading to a completely different solution.

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

Encountered the issue: "Received the error message 'MongooseServerSelectionError: Server selection timed out after 30000 ms.'"

I encountered the following error: MongooseServerSelectionError: Server selection timed out after 30000 ms while working with MongoDB Atlas. I attempted changing the useUnifiedTopology setting to false, which prevented my application from crashing. However ...

Blending Angular5 and AngularJS in Polymer

We are considering launching two new projects - one using Angular 5 and the other utilizing Polymer. The second project is intended to serve as a component library for reuse in not only the Angular 5 project but also in other AngularJS projects. After res ...

Attempting to wipe out a request using ajax to access relationship entities in a ruby on rails framework

I'm currently working on implementing an ajax request to delete a "budget" (known as "orçamento" in Portuguese). These budgets are associated with a "cadastre", where each cadastre can have multiple budgets. Below, you can find the components involve ...

The application is unable to recognize the CSS file

I am facing an issue where the design of my app is not displaying, even though the CSS file is located in the same folder. I'm unsure about what mistake I might have made! import React from 'react'; import classes from './Burger.css&ap ...

Error encountered when connecting to MongoDB: 'MongoServerSelectionError'

const uri = 'mongodb+srv:<username>//:<passwod>@chatapp-qrps3.azure.mongodb.net/test?retryWrites=true&w=majority' const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }) client.c ...

Encountering an SSL error while trying to establish a connection between a local server and the Heroku PostgreSQL

Currently, I am facing an issue with connecting to my postgreSQL database on Heroku from my express app. The connection functions properly when the express app is deployed on Heroku, but I encounter difficulties connecting to the database while running the ...

I'm having trouble importing sqlite3 and knex-js into my Electron React application

Whenever I try to import sqlite3 to test my database connection, I encounter an error. Upon inspecting the development tools, I came across the following error message: Uncaught ReferenceError: require is not defined at Object.path (external "path ...

Sending a reference to the event object within a JavaScript function

There are times when we need to use the event object in JavaScript. Below is an example of how we can pass the event: function test(e){ console.log(e); e.preventDefault(); console.log("You are not going to redirect"); } HTML <a href="www. ...

How can the radio button's checked property be bound to a boolean attribute of a component in Angular 2?

Is there a way to connect the checked property of a radio button to a boolean variable in a Component class? I would like the radio button in the template to be pre-selected if the boolean flag is true. I attempted to use <input type="radio" [(ngModel) ...

Guide to Producing an Unorthodox 3D Polygon Extruded Form using React-Three-Fiber

Up until now, I've only utilized useBox statement to create 3D rectangles. Is there a method available to generate something like a wooden piece in dimensions of "two by four" with cut ends at specific angles, akin to the image shown below? https://i ...

Understanding Arrays in Angular JSIn this article, we

I am new to working with Angular JS. Currently, I am populating an array and attempting to showcase its contents on the HTML page using ng-repeat. $scope.groupedMedia = []; // Elements are being added through a for loop. $scope.groupedMedia[year].push(r ...

Are you on the lookout for an Angular2 visual form editor or a robust form engine that allows you to effortlessly create forms using a GUI, generator, or centralized configuration

In our development team, we are currently diving into several Angular2< projects. While my colleagues are comfortable coding large forms directly with Typescript and HTML in our Angular 2< projects, I am not completely satisfied with this method. We ...

Using Express.js to import a SQL file

I am facing challenges while attempting to import an sql file into Express JS. I have tried various codes involving the mssql and fs modules, but none seem to be working as expected. fs.readFile(__dirname +'/database.sql', function (err, sqlFile ...

Is there a way to incorporate my init() function into a Karma test if the expect statement is designed for $scope?

One of my Karma test specs is set up like this: 'use strict'; describe('Controller: RegistrationCtrl', function () { beforeEach(module('stageApp')); var RegistrationCtrl, scope; beforeEach(inject(function ($controll ...

Increase the visibility of a div using Jquery and decrease its visibility with the "

Can anyone assist me with implementing a "show more" and "show less" feature for a specific div? I have put together a DEMO on codepen.io In the DEMO, there are 8 red-framed div elements. I am looking to display a "show more" link if the total number of ...

Tips for choosing Week Range values with Selenium WebDriver

Currently, I am working with Selenium WebDriver and I am trying to figure out how to select week range values from a dropdown menu at once. I have a dropdown called Period, which, when selected, automatically reveals additional dropdowns for From week and ...

Problem with image title in jQuery mobile

My code seems to be having an issue where the title does not display completely when hovering over it. For example, if the title is set as "The Value", only "The" is shown and not "The Value". Can anyone help me identify the mistake? Thank you in advance ...

Creating a 2D Image Display in three.js

I'm facing a challenge with my threejs project. My goal is to have a 2D image appear on the screen when I press a key. I've done some research but haven't been able to find a solution that works for me. The methods I've tried either don ...

Getting unique results from a knex.js INNER JOIN operation

Two tables, metadata and view_events, each have columns for config_id and config_type. The goal is to retrieve all unique view_events based on a user's email address, distinct by config_id and config_type, ordered by timestamp in descending order, lim ...

Leveraging EJS for embedding Google Maps API on a website

Currently, I am utilizing EJS to display the Google Maps API on a particular webpage. <!DOCTYPE html> <html> <head> <title></title> </head> <body> <div id="map"></div> <script> var ...