There is a calculator that takes values ​​from input and then performs the necessary mathematical calculations. Each of the input type = "number" , everything works fine, but when you type . , - stops working, the value returns as empty to the console. C , everything works fine. Tried to write pattern="\d+(,\d{2})?" , but apparently did not understand how it works and he did not give me anything. I need to ban input. и - , ну и был бы признателен, если бы объяснили как ограничить ввод до 2 знаков после , `to look like a price. Thank you. Here is my function and wrestling

 $('.calculator-button').on('click', function(){ var calculator = { priceGbo: $('#price_gbo').val(), priceFuel: $('#price_fuel').val(), priceGas: $('#price_gas').val(), priceMile: $('#expenses_mile').val(), priceDay: $('#expenses_day').val() }; var everydayEconomy = calculator.priceDay * (calculator.priceMile/100) * (calculator.priceFuel - calculator.priceGas * 1.1); var fiveYears = everydayEconomy * 1825; var feedbackTime = calculator.priceGbo / everydayEconomy; $('#everyday_economy').text(everydayEconomy.toFixed(0)); $('#fiveYears_economy').text(fiveYears.toFixed(0)); $('#feedback_time').text(feedbackTime.toFixed(0)); }); 
 .call-modal { width: 377px; height: 50px; background: #ffc107; color: black; font-size: 18px; font-family: "Pt Sans Bold"; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-align: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; cursor: pointer; margin-top: 45px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class = "calculator-inputs-left"> <div class = "calculator-inputs-left-row"> <div class = "calculator-inputs-left-row__text">Цена ГБО (грн.)</div> <div class = "calculator-inputs-left-row__input"> <input type = "number" pattern="\d+(,\d{2})?" class = "calculator-input" id = "price_gbo" min="0" value = ""> </div> </div> <div class = "calculator-inputs-left-row"> <div class = "calculator-inputs-left-row__text">Цена 1Л. бензина (грн.)</div> <div class = "calculator-inputs-left-row__input"> <input type = "number" class = "calculator-input" id = "price_fuel" min="0" value = ""> </div> </div> <div class = "calculator-inputs-left-row"> <div class = "calculator-inputs-left-row__text">Цена 1Л. газа (грн.)</div> <div class = "calculator-inputs-left-row__input"> <input type = "number" class = "calculator-input" id = "price_gas" min="0" value = ""> </div> </div> <div class = "calculator-inputs-left-row"> <div class = "calculator-inputs-left-row__text">Расход на 100 км пробега (л)</div> <div class = "calculator-inputs-left-row__input"> <input type = "number" class = "calculator-input" id = "expenses_mile" min="0" value = ""> </div> </div> <div class = "calculator-inputs-left-row"> <div class = "calculator-inputs-left-row__text">Средний суточный пробег (км)</div> <div class = "calculator-inputs-left-row__input"> <input type = "number" class = "calculator-input" id = "expenses_day" min="0" value = ""> </div> </div> </div> <div class = "call-modal calculator-button">Получить результат</div> <div class = "calculator-line"></div> <div class = "calculator-results"> <div class = "calculator-results-item"> <div class = "calculator-results-item__text">Ежедневная экономия (грн.)</div> <div class = "calculator-results-item__result" > <span id = "everyday_economy"></span> </div> </div> <div class = "calculator-results-item"> <div class = "calculator-results-item__text">За 5 лет экплуатации (грн.)</div> <div class = "calculator-results-item__result"> <span id = "fiveYears_economy"></span> </div> </div> <div class = "calculator-results-item"> <div class = "calculator-results-item__text">Срок окупаемости (дней)</div> <div class = "calculator-results-item__result"> <span id = "feedback_time"></span> </div> </div> </div> 

  • it’s not clear what to ban - Paulo Berezini
  • I also did not understand, to prohibit the sign "-" means to ban negative cisla? - Alexandr Maliovaniy 6:26 pm

2 answers 2

https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/RegExp write the pattern you need through regulars

  $('input[type="number"]').on('keyup focus', (event) => { let select = $(event.currentTarget); select.val(select.val().replace(/[^0-9]/gi,'').replace(/\s+/gi,', ')) + console.log( '#: '+select.val() ); }); 

if they explained how to limit the input to 2 characters afterwards, I would go here https://igorescobar.imtqy.com/jQuery-Mask-Plugin/#examples

    The pattern attribute specifies an expression to validate the data when submit form. That is, such a test and should not work when you enter each character. Plus, it does not filter input.

    To solve your problem, you need to write a script that:

    1. or will check the element's validity.valid , telling the user what it is

     let test = document.getElementById('test'); test.addEventListener('input', function () { if (this.validity.valid) this.classList.remove('err'); else this.classList.add('err'); }); 
     #test.err { border-color: red; } 
     <input id="test" type="number" pattern="^\d+(?:,\d{0,2})?$"> 


    2. either fully implements all validation / filtering logic

     document.addEventListener('DOMContentLoaded', pInpInit); function pInpInit() { let inputs = document.querySelectorAll('.input-regexp'); for (let inp of inputs) { inp.addEventListener('input', onPInpInput); inp.addEventListener('click', function () { this.lastCaretPos = this.selectionStart; }); } } function onPInpInput() { if (!this.value.length) { this.lastValue = ''; return; } let regxpr = this.dataset.regexp; if (!regxpr) return; regxpr = new RegExp(regxpr, 'i'); if (this.value.match(regxpr)) { this.lastValue = this.value; this.lastCaretPos = this.selectionStart; } else { this.value = this.lastValue || ''; let pos = this.lastCaretPos || 0; this.setSelectionRange(pos, pos); this.classList.remove('anim'); requestAnimationFrame(() => this.classList.add('anim')); } } 
     body { padding: 30vh 50px; } @keyframes color-fade { 0% { background-color: #f002; } 50% { background-color: #f002; } 100% { background-color: initial; } } .input-regexp { width: 150px; text-align: center; font: 20px sans-serif; } .input-regexp.anim { animation: color-fade 0.5s linear; } 
     <input class="input-regexp" type="text" data-regexp="^\d+(?:,\d{0,2})?$">&emsp; <input class="input-regexp" type="text" data-regexp="^\d+(?:[,.]\d{0,2})?$"> 

    In the second example, the left input statement accepts only a comma as a separator, and the right accepts both a comma and a period.