A Bootstrap plugin to create input spinner elements for number input

Overview

bootstrap-input-spinner

A Bootstrap / jQuery plugin to create input spinner elements for number input.

Demo page with examples

bootstrap-input-spinner Examples with floating-point and german localization

This version is compatible with Bootstrap 5, but we remain a Bootstrap 4 compatible version with the branch bootstrap4-compatible. npm package versions 3.x are Bootstrap 5 compatible, versions 2.x Bootstrap 4 compatible.

Features

The Bootstrap InputSpinner

  • is mobile friendly and responsive,
  • automatically changes the value when holding a button,
  • has internationalized number formatting,
  • allows setting a prefix or a suffix text in the input,
  • handles val() like the native element,
  • dynamically handles changing attribute values like disabled or class,
  • supports templates and custom editors, (new!)
  • dispatches change and input events on value change like the native element and
  • works without extra css, only Bootstrap 5 is needed.

Quickstart

Installation

Current version, Bootstrap 5 compatible

npm install bootstrap-input-spinner

Bootstrap 4 compatible version

npm install [email protected]

Or just download the GitHub repository and include src/bootstrap-input-spinner.js.

HTML

Create the element in HTML. The attributes are compatible to the native input[type="number"] element.

<input type="number" value="50" min="0" max="100" step="10"/>

Script

It is a jQuery plugin. So, enable the InputSpinner for all inputs with type='number' with the following script.

<script src="src/bootstrap-input-spinner.js"></script>
<script>
    $("input[type='number']").inputSpinner();
</script>

That's it. No extra css needed, just Bootstrap 5 and jQuery.

API Reference

HTML Attributes

<input type="number" value="4.5" min="0" max="9" step="0.1" data-decimals="2" data-suffix="°C"/>

Use these attributes to configure the behaviour

  • value // starting value on element creation
  • min // minimum value when stepping
  • max // maximum value when stepping
  • step // step size
  • inputmode // the "inputmode" of the input, defaults to "decimal" (shows decimal keyboard on touch devices)
  • data-decimals // shown decimal places
  • data-digit-grouping // "false" to disable grouping (thousands separator), default is "true"
  • data-prefix // show a prefix text in the input element
  • data-suffix // show a suffix text in the input element

The InputSpinner also handles the standard input attributes required, disabled, readonly and placeholder.

Create an instance in JavaScript

Use JavaScript to create the instance as a jQuery plugin. You may provide additional configuration in an object as a config parameter.

$(element).inputSpinner(config);

Configuration (props)

The default configuration is

var props = {
    decrementButton: "<strong>&minus;</strong>", // button text
    incrementButton: "<strong>&plus;</strong>", // ..
    groupClass: "", // css class of the resulting input-group
    buttonsClass: "btn-outline-secondary",
    buttonsWidth: "2.5rem",
    textAlign: "center", // alignment of the entered number
    autoDelay: 500, // ms threshold before auto value change
    autoInterval: 50, // speed of auto value change, set to `undefined` to disable auto-change
    buttonsOnly: false, // set this `true` to disable the possibility to enter or paste the number via keyboard
    keyboardStepping: true, // set this to `false` to disallow the use of the up and down arrow keys to step
    locale: navigator.language, // the locale, per default detected automatically from the browser
    editor: I18nEditor, // the editor (parsing and rendering of the input)
    template: // the template of the input
        '<div class="input-group ${groupClass}">' +
        '<button style="min-width: ${buttonsWidth}" class="btn btn-decrement ${buttonsClass} btn-minus" type="button">${decrementButton}</button>' +
        '<input type="text" inputmode="decimal" style="text-align: ${textAlign}" class="form-control form-control-text-input"/>' +
        '<button style="min-width: ${buttonsWidth}" class="btn btn-increment ${buttonsClass} btn-plus" type="button">${incrementButton}</button>' +
        '</div>'
}
decrementButton, incrementButton

HTML of the texts inside the buttons.

groupClass

Additional css class for the input-group of the rendered Bootstrap input.

buttonsClass

The css class of the buttons. Use it to style the increment and decrement buttons as described here. Maybe buttonsClass: btn-primary or btn-success or whatever type of buttons you want.

buttonsWidth

The width of the increment and decrement buttons.

textAlign

The text alignment inside the <input>.

autoDelay

The delay in ms after which the input automatically changes the value, when holding the increment or decrement button.

autoInterval

Speed of the value change when holding the button in ms. A lower value makes it faster.

buttonsOnly

In buttonsOnly mode (set true) no direct text input is allowed, the text-input gets the attribute readonly, but the plus and minus buttons still allow to change the value.

keyboardStepping

In keyboardStepping mode (set true) allows the use of the up/down arrow keys to increase/decrease the number by the step.

locale

Used to format the number in the UI. Detected automatically from the user's browser, can be set to "de", "en",… or " de_DE", "en_GB",….

editor (new!)

An Editor defines, how the input is parsed and rendered. The default editor of the spinner is the I18nEditor, which renders and parses an internationalized number value. There are custom editors in /src/custom-editors.js. An Editor must implement the two functions parse(customValue), to parse the input to a number and render(number) to render the number to the spinner input.

The simplest custom Editor is the RawEditor, it renders just the value und parses just the value, without any changes, like a native number input. It looks like this:

var RawEditor = function (props, element) {
    this.parse = function (customFormat) {
        // parse nothing
        return customFormat
    }
    this.render = function (number) {
        // render raw
        return number
    }
}

props is the configuration of the spinner and element is the original HTML element. You can use these values for the configuration of the Editor, like in I18nEditor, which uses props for the language and element for the attributes.

The TimeEditor renders and parses the number to time in hours and minutes, separated by a colon.

bootstrap-input-spinner Supports custom editors to parse and render everything

template (new!)

To modify the look completely, you can use the template parameter. There is an example about this on the Demo Page.

Programmatic change and read of value

To change or read the value just use the jQuery val() function on the input, like this

var currentValue = $(element).val() // read
$(element).val(newValue) // write

Hint: Reading the value in vanilla JS with element.value will also work, but to set the value you have to use element.setValue(newValue) or $(element).val(newValue)

Handling attributes

The attributes min, max, step, decimals, placeholder, required, disabled, readonly and class are handled dynamically. The class attribute value is dynamically copied to the input element.

Sizing

If the original elements class is set to form-control-sm of form-control-lg the class of the resulting input-group is dynamically set to input-group-sm or input-group-lg.

Events

The InputSpinner handles input and change events like the native element.

Event handling with vanilla JavaScript

element.addEventListener("change", function (event) {
    newValue = this.value
})

Event handling with jQuery syntax

$(element).on("change", function (event) {
    newValue = $(this).val()
})

Methods

Methods are passed as string values instead of the options object.

destroy

Removes the InputSpinner and shows the original input element.

$(element).inputSpinner("destroy")

Minified version

I don't provide a minified version because I think it should be up to the using programmer to create minified versions, with all the used script sources concatenated to one file.

But, if you want it, it is easy to create your minified version with uglify: https://www.npmjs.com/package/uglify-js

Just install uglify

npm install uglify-js -g

and then in the src-folder

uglifyjs bootstrap-input-spinner.js --compress --mangle > bootstrap-input-spinner.min.js

Violà! :)

Browser support

The spinner works in all modern browsers and in the Internet Explorer. Not tested with IE < 11.

For older browsers (IE 9 or so), that doesn't support Intl, when you get an error message like "Intl is not defined" (See issue #34), just use a shim or polyfill like Intl.js, and it works.

You may want to check out my further Bootstrap and HTML extensions

Comments
  • Add inputmode updating to decimal / input defined property

    Add inputmode updating to decimal / input defined property

    This would keep all the formatting logic about localization since the type stays text, but would show the numeric keyboard on mobile devices that supports this attribute.

    As discussed in #32

    Fixes #31 (for the great majority of browsers at least, some are still not supporting this tag, but probably will in the future)

    opened by V-ed 12
  • Spinner Not Stopping on max value

    Spinner Not Stopping on max value

    My spinner will not stop on max amount. It goes 2 steps above every time if you just hold it down. Once you click back on it goes to max and then starts down if you pressing down. This happens to all the spinners I have on the page also.

    bug 
    opened by stevensoftwaredev 11
  • Issues with Bitwarden (Password Manager)

    Issues with Bitwarden (Password Manager)

    "A picture is worth a thousand words".

    I am trying to show the issue with an animated gif here: input_fromDesktop

    Here is a typical example of bootstrap-input-spinner rendered in a form and working in a dekstop computer. What i am trying to do, is to type the amount of "3,45" or "3.45" (if you prefer). As you can see by the keystrokes i haved demostrated, it's almost impossible. I made some tries and then finally i achieve to type in correctly. I don't think the ideal solution is to use the buttons for all cases. Think if you have to type in the amount of ex. 645 or 4 589

    But what about a regular user, not so much experienced ?

    You can try yourself in example page of-course Demo example page

    P.S. It doesn't seem the same issue from mobile.

    wontfix 
    opened by perarg 10
  • "Invalid regular expression" error when thousandSeparator is empty string

    How to reproduce:

    1. Change system region format to Russian.
    2. Click on input spinner to input value by typing
    3. Type any number

    You should see an error: bootstrap-input-spinner.js:256 Uncaught SyntaxError: Invalid regular expression: /\/: \ at end of pattern at new RegExp (<anonymous>) at parseLocaleNumber (bootstrap-input-spinner.js:256) at HTMLInputElement.<anonymous> (bootstrap-input-spinner.js:113)

    Reasoning On Russian locale, there's no separator for thousands. Hence,this line var thousandSeparator = numberFormat.format(1111).replace(/1/g, '') produces an empty string. Then the next line new RegExp('\\' + thousandSeparator, 'g'), '') makes a regexp /\/, which makes an error and doesn't change the input spinner val.

    opened by Roman- 10
  • "An invalid form control with name='' is not focusable" when "required"

    I found the solution like this ;

    function updateAttributes() { // copy properties from original to the new input $input.prop("name", $original.prop("name")) $original.removeAttr("name") $input.prop("required", $original.prop("required")) $input.prop("placeholder", $original.prop("placeholder")) . . .

    opened by mucahittopal 9
  • Bootstrap 4 vertical alignment

    Bootstrap 4 vertical alignment

    I'm using bootstrap 4 and displaying this in an html table cell. In the attached image you will note that the vertical alignment is different from the other controls in the table row. The other inputs around it are all "form-control-sm" and I have initialized as follows:

    $("input[type='number']").inputSpinner({ groupClass: "input-group-sm", buttonsWidth: "0.5rem" });

    Capture

    opened by jrichview 6
  • Cannot read value when id contains certain characters

    Cannot read value when id contains certain characters

    <input type="number" id="qty:CRE:S" class="form-control-sm" value="0" min="0" max="1000" step="1"/>

    $('#qty:CRE:S').val() results in undefined

    Changing : to *, . or _ results in the same, but replacing with an alphanumeric character will allow value to be read

    opened by swayton 5
  • Bug on Safari and iOs devices

    Bug on Safari and iOs devices

    Hello,

    it seems that Apple has stopped using the Intl librairy :

    line 238 : ReferenceError: Can't find variable: Intl

    Is there a way to fix it ?

    Thank you

    opened by Fred-Guile 5
  • plus and minus icons are not showing

    plus and minus icons are not showing

    Hello there

    I'm running this in localhost. The plus and minus sign of the spinner are not showing up. The browser only shows a default spinner

    here is my page

    `

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="css/styles.css" >
    
    <!-- JQuery -->
    <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
    
    <!-- Extra scripts for BS  -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    
    <script src="http://localhost/front-end/js/bootstrap-input-spinner.js"></script>
    
    <script>
        jQuery("input[type='number']").inputSpinner()
    </script>
    
    <script>
      jQuery( function() {
        jQuery( ".datepicker" ).datepicker();
      } );
    </script>
    
    <div class="form-container">
    
      <form class="form-horizontal" action="" method="POST">
    
          <!-- Number of adults-->
          <div class="form-group">
            <label class=" control-label" for="adults">Adults</label>
            <div class="">
              <input name="adults" type="number" value="0" min="0" max="5" step="1" />
            </div>
          </div>
    
          <!-- Number of children -->
          <div class="form-group">
            <label class="control-label" for="children">Children</label>
            <div class="">
               <input name="children" type="number" value="0" min="0" max="5" step="1"/>
            </div>
          </div>
    
          <!-- Number of infants -->
          <div class="form-group">
            <label class=" control-label" for="infants">Infants</label>
            <div class="">
              <input name="infants" type="number" value="0" min="0" max="5" step="1"/>
            </div>
          </div>
    
         
    
          </fieldset>
          </form>
    
         </div>
    

    `

    opened by hasintha 5
  • Using a number keyboard on mobile devices / setting the input pattern.

    Using a number keyboard on mobile devices / setting the input pattern.

    As currently written, the plugin has the "type" property of the resulting input hard-coded as "text". This creates a type="text" input regardless of the original input type (for example, "number"). This hurts the "mobile-friendliness" claim of the addon because if a user tries to interact with an input that is supposed to be of a particular type, the mobile browser will instead revert to full-text input.

    opened by jboyer87 5
  • Button wrapping

    Button wrapping

    Spinner is a nice control (thanks!), but I'm having problems with the plus button (button on right hand side of the text input) wrapping to underneath the text input. Obviously that makes it look pretty screwy.

    My text input is inside of a td and I have set a specific width on it in order to keep it from hogging more space than it needs to enter a 2-digit age. Looks great when my browser is maxed, but as I shrink the width, not so great.

    opened by jrichview 5
  • Minification using Microsoft Visual Studio 22 causes

    Minification using Microsoft Visual Studio 22 causes "Identifier has already been declared Error"

    The issue only presented itself when minified and seems to be a scope related problem when defining variables in the else statement that are to be used outside the scope of the else statement. The actual response from the error provided precious little information other than the delaraction error pointing to this piece of the code.

    == Issue if (this["bootstrap-input-spinner"]) { console.warn("element", this, "is already a bootstrap-input-spinner") } else { -- variables defined here were causing the issue }

    == Quick Fix if (this["bootstrap-input-spinner"]) { console.warn("element", this, "is already a bootstrap-input-spinner") return; } -- Code continues here not contained within else statement without issue particularly when minified.

    opened by gallge01 1
  • Change event of an input spinner triggers the change events of all other input spinners

    Change event of an input spinner triggers the change events of all other input spinners

    Version: 2.2.0 Steps to reproduce:

    1. Create 2 input spinners
    2. Attach change event handlers to both spinners
    $("#spinnerA").change(function () {
        console.log("Hello");
    });
    $("#spinnerB").change(function () {
        console.log("World");
    });
    
    1. Click on either one of the spinners' button (up or down).
    2. The console will print both Hello and World.

    Expected result(s): The console should only print EITHER Hello or World depending on which button of which spinner is clicked. NOT both.

    One version prior (2.1.2) doesn't have this issue.

    bug 
    opened by DamienLaw 0
  • Semicolon is added at the start instead of at the end of the source.

    Semicolon is added at the start instead of at the end of the source.

    There is no semicolon at the end of the file https://github.com/shaack/bootstrap-input-spinner/blob/29b09b4be6bf0dd4af0a0a0cb55594093eeec329/src/bootstrap-input-spinner.js#L372

    It is however added at the beginning https://github.com/shaack/bootstrap-input-spinner/blob/29b09b4be6bf0dd4af0a0a0cb55594093eeec329/src/bootstrap-input-spinner.js#L7

    This library, among many other third party libraries are concatenated/bundled together into a big file of libraries to allow browser download more efficiently. Without a semicolon at the end, browser is throwing errors when there are other files concatenated after this library.

    image

    opened by DamienLaw 1
  • Issue on responsive

    Issue on responsive

    Hello, i have an issue only on responsive with bootstrap-input-spinner.js plugin i'm using to create input spinner elements for number input. You can see a demo in this link https://www.fabiotoscano.it/ProjectRiordina/ where in desktop version works correctly: https://ibb.co/8cWsg1D Issue is from mobile in smaller devices where i need to expand column

    1. https://ibb.co/3vDYfnL click on details for expand cell
    2. https://ibb.co/zFynyFJ Input button not works

    Any suggestion about the issue? Regards

    opened by fabioweb90 1
Releases(v2.1.2)
  • v2.1.2(Jun 14, 2021)

    With version 3.x we will switch the compatibility to bootstrap 5. However, the bootstrap 4 compatibility will remain with the versions 2.x and with this release. Also for the bootstrap 4 compatibility I created the branch bootstrap4-compatible.

    Source code(tar.gz)
    Source code(zip)
Owner
Stefan Haack
My code is your code
Stefan Haack
Create a deep copy of a set of matched elements with the dynamic state of all form elements copied to the cloned elements.

jq-deepest-copy FUNCTION: Create a deep copy of a set of matched elements while preserving the dynamic state of any matched form elements. Example Use

Michael Coughlin 5 Oct 28, 2022
jquery-input-mask-phone-number.js - A simple, easy jquery format phone number mask library

jquery-input-mask-phone-number A jQuery Plugin to make masks on input field to US phone format. Quick start 1. Add latest jQuery and jquery-input-mask

Raja Rama Mohan Thavalam 12 Aug 25, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Extends Bootstrap Tooltips and Popovers by adding custom classes. Available for Bootstrap 3 and Bootstrap 4.

Bootstrap Tooltip Custom Class Extends Bootstrap Tooltips and Popovers by adding custom classes. Available for Bootstrap 3 and Bootstrap 4. Define you

Andrei Victor Bulearca 14 Feb 10, 2022
A simple Form Validation Utility for Bootstrap 3, Bootstrap 4, and Bootstrap 5 for Humans.

bootstrap-validate A simple Form Validation Utility for Bootstrap 3, Bootstrap 4, and Bootstrap 5 for Humans. ?? Support us with Developer Merchandise

null 138 Jan 2, 2023
Multiplies a number by zero. Useful for when you need to multiply a number by zero

multiply-by-zero Multiplies a number by zero. Useful for when you need to multiply a number by zero Please consider checking out the links of this pro

Dheirya Tyagi 2 Jul 3, 2022
proxy 🦄 yxorp is your Web Proxy as a Service (SAAS) Multi-tenant, Multi-Threaded, with Cache & Article Spinner

proxy ?? yxorp is your Web Proxy as a Service (SAAS) Multi-tenant, Multi-Threaded, with Cache & Article Spinner. Batteries are included, Content Spinning and Caching Engine, all housed within a stunning web GUI. A unique high-performance, plug-and-play, multi-threaded website mirror and article spinner

4D/ҵ.com Dashboards 13 Dec 30, 2022
A pure javascript class for paginating through any number of DOM elements

PurePajinate A pure javascript class for paginating through any number of DOM elements. Inspired by Pajinate, a plugin for jQuery. Options Option Type

Olivier Buisard 3 Nov 21, 2022
The jQuery plugin that brings select elements into the 21st century with intuitive multiselection, searching, and much more. Now with Bootstrap 5 support.

bootstrap-select The jQuery plugin that brings select elements into the 21st century with intuitive multiselection, searching, and much more. Now with

SnapAppointments 9.7k Dec 30, 2022
The jQuery plugin that brings select elements into the 21st century with intuitive multiselection, searching, and much more. Now with Bootstrap 5 support

bootstrap-select The jQuery plugin that brings select elements into the 21st century with intuitive multiselection, searching, and much more. Now with

SnapAppointments 9.7k Dec 30, 2022
Bootstrap Colorpicker is a modular color picker plugin for Bootstrap.

Bootstrap Colorpicker Bootstrap Colorpicker is a modular color picker plugin for Bootstrap 4. THIS PROJECT IS NOT MAINTAINED ANYMORE. After almost 10

Javi Aguilar 1.4k Dec 22, 2022
jQuery tags input plugin based on Twitter Bootstrap.

Bootstrap Tags Input Bootstrap Tags Input is a jQuery plugin providing a Twitter Bootstrap user interface for managing tags. Current stable version: v

null 26 Dec 21, 2022
`raaghu-mfe` is an opensource micro front end framework built on top of `raaghu-elements`, Bootstrap 5 and Storybook offering highly customizable UI components and built-in pages

`raaghu-mfe` is an opensource micro front end framework built on top of `raaghu-elements`, Bootstrap 5 and Storybook offering highly customizable UI components and built-in pages. Raaghu mfe can be used as a base to build complex components and UI layouts whilst maintaining a high level of reusability,flexibility with ease of maintenance.

Wai Technologies 160 Dec 30, 2022
Formats message strings with number, date, plural, and select placeholders to create localized messages

Formats message strings with number, date, plural, and select placeholders to create localized messages. Small. Between 700 bytes and 1.3 kilobytes (m

Marcis Bergmanis 35 Oct 30, 2022
Simple tag input for Bootstrap

Tagin Simple tag input for Bootstrap. Supports bootstrap v4 and v5. Demo: https://tagin.netlify.app/ Features Custom separators Enable/disable duplica

Erwin Heldy G 37 Sep 28, 2022
An enhanced HTML 5 file input for Bootstrap 5.x/4.x./3.x with file preview, multiple selection, and more features.

bootstrap-fileinput An enhanced HTML 5 file input for Bootstrap 5.x, 4.x, and 3.x with file preview for various files, offers multiple selection, resu

Kartik Visweswaran 5.2k Jan 3, 2023
A jQuery plugin wrapper around Bootstrap Alerts, to create Notifications (Toasts)

bootstrap-show-notification A jQuery plugin wrapper around Bootstrap 4 Alerts, to show them as toasts (also called notifications) dynamically from Jav

Stefan Haack 10 Aug 22, 2022