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.
Advertisement
Answer
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" />