Best regard. I have a problem and it is the following:
I want to call a function JavaScript
that only allows to write numbers in a field input
, but I don't know how to do it.
Thanks in advance for your answers.
function justNumbers(e){
var keynum = window.event ? window.event.keyCode : e.which;
if ((keynum == 8) || (keynum == 46))
return true;
return /\d/.test(String.fromCharCode(keynum));
}
var pais = document.getElementById('pais');
var telf = document.getElementById('telf');
pais.onchange = function(e) {
telf.value = this.value;
if((this.value).trim() != '') {
telf.disabled = false;
} else {
telf.disabled = true;
}
}
telf.onkeyup = function(e) {
var nums_v = this.value.match(/\d+/g);
if (nums_v != null) {
this.value = '+'+((nums_v).toString().replace(/\,/, ''));
} else {
this.value = pais.value;
}
this.value = this.value.replace(/(\+\d{2})(\d)/, '$1 $2');
}
I want this function to be executed in this input
:
<label">Documento</label>
<input type="text" class="form-control" name="documento" value="<?php
if(isset($documento)) echo $documento; ?>" required>
Obviously using a numeric control is the best option, but if you want to do it with JavaScript (for issues specific to your implementation) I think the answer is in your code.
You have previously connected the controls with id's "country" and "tel" with the events
onchange
andkeyup
respectively.To connect this control you could do the following:
document.getElementsByName("documento")[0].addEventListener('change', justNumbers);
For reasons of code reuse, I recommend that you set a specific class in the control, so that you can use it in other controls.
This way you can place more elements
input
with the "numeric" class and control them all with your function.Another suggestion is that you use the event
keyup
to control the backspace and pasting from the clipboard.Cheers!
If what you want to do is execute the function every time you type a letter in the
input
, you use the functiononchange=MyFunction()
, if what you want is to execute the function after pressing a buttononclick=MyFunction()
itonclick
goes in the button label.I hope it helps you.
You can use a
input
typenumber
that restricts you to using numbers only and is native tohtml
: