To accept only a numeric value ( integer or float ) value in the HTML text field we make use of the following
Javascript : Program to accept only a decimal / float input.
<!DOCTYPE html>
<html>
<body>
<script>
function only_decimal(event) {
if (event.key === 'Backspace' || event.key === 'Delete'
|| event.key === 'Tab' || event.key === 'Escape'
|| event.key === 'Enter' || event.key === '.'
|| event.key === 'ArrowLeft' || event.key === 'ArrowRight' ||
isFinite(event.key)) {
var decimal_str = document.getElementById("id_decimal_field").value;
if (decimal_str.indexOf(".") != -1 && event.key === '.') {
event.preventDefault();
} else {
// Accept the first dot(".")
return;
}
} else {
event.preventDefault();
}
}
function DisplayCost() {
document.getElementById("Cost").innerHTML = "Entered Amount: " + document.getElementById("id_decimal_field").value;
}
</script>
<h2>Accept decimal / float values</h2>
<label>Enter Cost: </label>
<input type="text" name="decimal_field" id="id_decimal_field" class="only_decimal"
maxlength="20" onkeypress="return only_decimal(event)"/>
<br><br>
<button onclick="DisplayCost()">Submit</button>
<br>
<p id="Cost"></p>
</body>
</html>
Try it out :
https://jsfiddle.net/algotree/9o1uvt6m/