myrius
myrius

Reputation: 11

Replace dot and comma while typing and Replace in Inputfield

I would like to disallow the user to type comma or dot while typing in the input field of the type number.

I have already searched and found solution, but it does not work.

If I type e.g. point, no matter which of the two solutions below, the input field is cleared.

This is my input field

<input type="number" class="form-control numbersOnly" name="angebot" id="angebot" min="1" step="1"  placeholder="<?php the_field('language_shop_detail_button_counter_offer_placeholder', 'option'); ?>">

Those are the 2 approaches that don't work.

jQuery('.numbersOnly').keyup(function () { 
    this.value = this.value.replace(/[^0-9\.]/g,'');
});

and

$('.angebotAbgebenContainer #angebot').keyup(function(event) {

    var current = $(".angebotAbgebenContainer #angebot").val();
    console.log("current", current);
    
    
    var replaced = current.replace(/\./g, "");
    console.log("replaced", replaced);
    
    //replaced = parseInt(replaced);
    
   // $('.angebotAbgebenContainer #angebot').val(replaced);
    
 
});

Those are the 2 approaches that don't work. As soon as I make a point, in both approaches, the input field is cleared.

But what I want is, if someone tries to type a point or a comma, it doesn't appear and if someone copy pastes a number, the comma and point must also be gone.

Upvotes: 0

Views: 1540

Answers (3)

Subhashis Pandey
Subhashis Pandey

Reputation: 1538

Can use prevent default as below, and on change for paste

$(function() {
  $('#angebot').on('keydown', function(e) {
    if (e.keyCode == 188 || e.keyCode == 110) { // 188 for comma, 110 for point
        e.preventDefault();
    }
  }).on('change', function() {
    var self = $(this);
    self.html( self.html().replace(new RegExp(',', 'g'),'') ); // Remove all commas.
    self.html( self.html().replace(new RegExp('.', 'g'),'') ); // Remove all points

  });
})

Upvotes: 0

M. Haseeb Akhtar
M. Haseeb Akhtar

Reputation: 867

If you are going to input numeric values in the input only, might as well disable the inputting of all keys except numeric, like:

$(document).on("keypress keyup blur", ".numbersOnly", function (event) {
    $(this).val($(this).val().replace(/[^\d].+/, ""));
    if ((event.which < 48 || event.which > 57)) {
        event.preventDefault();
    }
});

Where 48 - 57 represents keycodes, you can find all keycodes here.

Upvotes: 1

mplungjan
mplungjan

Reputation: 177746

This works for me

Note it is type text

$('#angebot').on("input",function(event) {
  var current = $(this).val();
  console.log("current", current);
  var replaced = current.replace(/[\D\.,]/g, "");
  console.log("replaced", replaced);
  $(this).val(replaced);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="text" id="angebot" />

Upvotes: 1

Related Questions