JSFiddle - React, Tailwind, and code Playground
by Oleh Kotsubko
HTML
<div class="goods-count-block">
<form action="#">
<fieldset>
<button type="button" class="btn dec">-</button>
<input type="text" class="goods-amount-input" value="1 шт.">
<button type="button" class="btn inc">+</button>
</fieldset>
</form>
</div>
<span id="console"></span>
JavaScript
$('.goods-count-block').on('click', function(event){
var $target = $(event.target);
var inputVal = $(this).find('.goods-amount-input').val();
var currentVal = Number(inputVal.replace(/шт(\.)?/g, ""));
if($target.hasClass('dec') && currentVal >= 2) {
currentVal--;
$(this).find('.goods-amount-input').val(currentVal+' шт.');
$('#console').text(currentVal);
} else if ($target.hasClass('inc')) {
currentVal++;
$(this).find('.goods-amount-input').val(currentVal+' шт.');
$('#console').text(currentVal);
}
});
$('.goods-amount-input').on('focus', function(){
$(this).val('');
});
$('.goods-amount-input').on('blur', function(){
var inpVal = $(this).val();
if(inpVal == 0) {
$(this).val('1 шт.');
} else {
$(this).val(inpVal+' шт.');
}
});
$(".goods-amount-input").on('keyup keydown', function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A, Command+A
(e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});