When I click on the input <input type="number" id="n" /> ; type some key on keypress function of the input. Then typing . though it display on the input but I cannot get see . in $('#n').val().
For example after typing: 123. Then $('#n').val() only return 123.
Is there any attribute of <input type="number" /> that I can get its raw value which is 123. rather than 123?
$("#n").on("keypress", function(event) {
console.log($("#n").val());
});
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<input type="number" pattern="[0-9]{1,2}([\.][0-9]{1,2})?" id="n" step="0.01" />
UPDATE:
input MUST have type number to allow it to showing number input only on softkeyboard on mobile web.It should check for pattern 99.99 and work as below:
Without detect the existance dot(.) how can I detect the case of typing multiple . consecutively ?
I've myself faced this issue earlier. Maybe this can help:
$("#n").on("keyup", function(event){
var val = $('#n').val();
if(event.keyCode == 190) {
val+='.';
}
console.log(val);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<input type="number" id="n" />
</body>
</html>
<input type="number"
min="0"
max="999"
step="0.000001"
pattern="[0-9]{1,2}([\.][0-9]{1,2})?"
id="n" />
This Should Solve your problem. Use FocusOut event to capture the value
In order to get a value from input with type numeric, when value ends with a dot, you need to use a hacky solution that requires you to listen to 'onKeyUp' event. This behavior is intentional since numeric input should only return valid numbers.
Here is my implementation of described solution:
const resultContainer = document.querySelector("#result");
let value = null;
const updateValue = (event) => {
const DOT_KEY_CODE = 190;
const BACKSPACE_KEY_CODE = 8;
let newValue = event.currentTarget.value;
if (newValue === "" || newValue === null) {
if (event.keyCode === DOT_KEY_CODE) {
newValue = value.toString() + ".";
} else if (event.keyCode === BACKSPACE_KEY_CODE) {
const valueParts = value.toString().split(".");
const DECIMAL_PART = 1;
const decimalPlaces = valueParts.length > 1 ? valueParts[DECIMAL_PART].length : 0;
const LAST_DECIMAL_PLACE = 1;
if (decimalPlaces === LAST_DECIMAL_PLACE) {
const REMOVE_ONE_CHAR = 1;
newValue = value.toString().substring(0, value.toString().length - REMOVE_ONE_CHAR);
}
}
}
value = newValue;
resultContainer.innerHTML = newValue;
};
<input type="number" onKeyUp="updateValue(event)" />
<div>Received value: <span id="result"></span></div>