Converting the number to a string

I have an issue as input cell is defined as a number type. Quantity should be digits and only numbers.
I try to eliminate quantity value such as 8.9 (US) or 8,9 (EU) and set validation control.

An example:

<input type="number" name="quantityfield" id="quantity" />

How to convert the number to a string by adding number.toString().

JavaScript is the following:

  $(".checkout").on("keyup", "#quantity", function()
   {
    var price = +$(".price").data("price");
    var quantity = +$(this).val();
    var total = (price * quantity).toLocaleString(
        'de-DE',
     {style: 'currency', currency: 'EUR'}
    )
    $("#result").text(total);
   }
  )

I am not sure if I understood you question correct but you can allow the input field to only accept digits by

  $(".checkout").on("keyup", "#quantity", function()
   {
    $(this).val($(this).val().replace(/[^0-9]/, ' ');
    var price = +$(".price").data("price");
    var quantity = +$(this).val();
    var total = (price * quantity).toLocaleString(
        'de-DE',
     {style: 'currency', currency: 'EUR'}
    )
    $("#result").text(total);
   }
  )

Hi @toplisek, you can add a step="1" attribute to allow only integer values; the user can still enter decimal values then, but the field will be considered invalid and a step mismatch error will be reported when submitting the form.

If you want to “correct” values right during input though, you might just revert it to the last valid value like so:

<input id="quantity" type="number" step="1">
const quantity = document.getElementById('quantity')
let value = quantity.value

quantity.addEventListener('input', () => {
  if (quantity.validity.valid) {
    value = quantity.value
  } else {
    quantity.value = value
  }
})

fiddle

1 Like

I’m not sure but I tested your code and gives me an error:
SyntaxError: missing ; before statement

What should be modified to work quantiy as I have added addEventListener but it will all the time filled in number like 1, 2…etc

var $ = jQuery;
$(".checkout").on("keyup", "#quantity", function()
 {
  var price = +$(".price").data("price");
  const valquantity = document.getElementById('quantity')
  let value = valquantity.value
  valquantity.addEventListener('input', () =>
   {
    if (valquantity.validity.valid) {
     value = valquantity.value
    } else {
     valquantity.value = value
    }
   }
  )
  var quantity = +$(this).val();
  var total = (price * quantity).toLocaleString(
   'de-DE',
   {style: 'currency', currency: 'EUR'}
  )
  $("#result").text(total);
 }
)

There doesn’t appear to be a syntax error in the code you posted (see linter below)… could you provide a fiddle or the like?

A problem with your logic however is that you’re adding input event listeners inside the keyup event listener, so the former will pile up on every keyup event. Instead, the listeners should either be next to each other, or merged to a single event handler… for example:

let validValue = $('#quantity').val()

$('.checkout').on('keyup', '#quantity', function () {
  // Validity check
  if (this.validity.valid) {
    validValue = this.value
  } else {
    this.value = validValue
  }

  // Other logic
  const price = +$('.price').data('price')
  const quantity = +$(this).val()
  const total = (price * quantity).toLocaleString(
    'de-DE',
    { style: 'currency', currency: 'EUR' }
  )
  $('#result').text(total)
})

I have tested your suggested code and element position. When I put 2 as quantity filled in value I can not delete and modify. I’m not sure if this is a browser detection or JavaScript related. On the right-hand side I see arrows UP/DOWN to in/decrement value but when I use BACKSPACE to modify number it will not be possible to modify with the new value. The fomat:TYPE number.

An example: if I put 9 I can not use BACKSPACe and modify to 2. Maybe some refresh AJAX can help to refresh those numbers.!

When tested inside Mozilla it will be shown also another field. Probably Mozilla issue as Chrome is not showing such issue.
doubleinput1

Same problem occurs on Safari. Thats why I avoid the type=“number” fields and validate it by myself as shown in my answer.

Hm I can’t reproduce the issue in the above fiddle… do you maybe have an additional required constraint on your input element? In that case you might check for a step mismatch specifically:

const quantity = document.getElementById('quantity')
let validValue = quantity.value

quantity.addEventListener('input', () => {
  if (quantity.validity.stepMismatch) {
    quantity.value = validValue
  } else {
    validValue = quantity.value
  }
})

Or, if this is indeed a validity state issue, only reset non-empty values:

if (value && quantity.validity.stepMismatch) {
  quantity.value = validValue
} else {
  validValue = quantity.value
}

I have indeed element required. It is used due to Parsley validation which is requested due to validation (integer numbers) but it will also influence validation inside checkout.

Code is working when I remove element required which is demanded for Parsley validation and controls empty value.

So, we can use use element called required and more complicated code like Thallius commented:

type=“text”

and add validation

$(this).val($(this).val().replace(/[^0-9]/, ' ');

like:

$(".checkout").on("keyup", "#quantity", allowOnlyNumbers, function()
 {
  var price = +$(".price").data("price");
  var quantity = +$(this).val();
  function allowOnlyNumbers() {
   q.value = q.value.replace(/[^0-9]/g, "");
   if(q.value=="") q.value = "0";
   document.getElementById("result").innerText = (q.value * price).toFixed(2);
  }
  var total = (price * quantity).toLocaleString(
   'de-DE',
   {style: 'currency', currency: 'EUR'}
  )
  $("#result").text(total);
 }
)

Can be improved in this case as we use type TEXT?

what’s q? You dont define it anywhere.

Why are we defining a function allowOnlyNumbers inside the function that is supposed to be passed a data value called allowOnlyNumbers?

Why are we replacing the innerText of the result element inside the function, and then replacing it again at the end of the main event function?

1 Like

I’m just experimenting with the code from Thallius. Thank you Thallius for this code and an option about type text.
He put the following code:

$(".checkout").on("keyup", "#quantity", function()
 {
  $(this).val($(this).val().replace(/[^0-9]/, ' ');
   var price = +$(".price").data("price");
   var quantity = +$(this).val();
   var total = (price * quantity).toLocaleString(
    'de-DE',
    {style: 'currency', currency: 'EUR'}
   )
   $("#result").text(total);
   }
  )

As it is more complex code and variables can be set it is just suggestion how to improve it as we are using now text as TYPE. So, we can add a function called allowOnlyNumbers and use requested inside Parsley but code is just suggestion.

  function allowOnlyNumbers() {
   q.value = q.value.replace(/[^0-9]/g, "");
   if(q.value=="") q.value = "0";
   document.getElementById("result").innerText = (q.value * price).toFixed(2);
  }