Skip to content

Instantly share code, notes, and snippets.

@Korveld
Last active September 9, 2020 10:09
Show Gist options
  • Select an option

  • Save Korveld/fe7f3b6489971c9bc1c8d4a53618837f to your computer and use it in GitHub Desktop.

Select an option

Save Korveld/fe7f3b6489971c9bc1c8d4a53618837f to your computer and use it in GitHub Desktop.
Count up and down with buttons
jQuery(document).ready(function ($) {
$('.counter__input').on('keypress keyup blur', function (e) {
$(this).val( $(this).val().replace(/[^\d].+/, "") )
if ((e.which < 48 || e.which > 57)) {
e.preventDefault()
}
})
var addInput = '.counter__input' //This is the id of the input you are changing
var n = 1 //n is equal to 1
//Set default value to n (n = 1)
$(addInput).val(n)
//On click add 1 to n
$('.counter__arrow--up').on('click', function(e) {
e.preventDefault()
$(addInput).val(++n)
})
$('.counter__arrow--down').on('click', function(e) {
e.preventDefault()
//If n is bigger or equal to 1 subtract 1 from n
if (n >= 1) {
$(addInput).val(--n)
} else {
//Otherwise do nothing
}
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment