Avoid enter dot in input field - javascript

I have an input field which is of number type, when I enter the dot I am not getting the value. So what I am trying to achieve is the I don't want the user to enter dot on the input field
function handleChange (value) {
console.log(value)
}
<input type="number" onchange="handleChange(this.value)"/>
on each number entering I am getting the value, but when I type dot (.), I am not getting how can I block this when user type it

<input name="num" type="number" min="1" step="1" onkeypress="return event.charCode >= 48 && event.charCode <= 57">
referance from this url
https://stackoverflow.com/a/44379790/4316212

Add This oninput="this.value = this.value.replace(/[^0-9]/, '')"
function handleChange (value) {
console.log(value)
}
<input type="number" onchange="handleChange(this.value)" oninput="this.value = this.value.replace(/[^0-9]/, '')"/>

if you want to block '.' you can use this way,
function handleChange (value) {
console.log(value)
}
var inputBox = document.getElementById("inputBox");
var invalidChars = [
".",
];
inputBox.addEventListener("keydown", function(e) {
if (invalidChars.includes(e.key)) {
e.preventDefault();
}
});
<input type="number" id="inputBox" onchange="handleChange(this.value)/>

It is generally not a good idea to use inline event handlers.
For more control you should check/use the atributes of a number input.
If you want to completely control the input, use a readonly field and handle it using your own handler. Here's a snippet using event delegation. It uses the step attribute from the number input field for adding/subtracting.
document.addEventListener('click', handle);
function handle(evt) {
if (evt.target.dataset.numinput) {
const inp = document.querySelector(`#num`)
inp.value = ( +inp.value + +(`${evt.target.dataset.numinput}${inp.step}`) )
.toFixed(2);
}
}
<input id="num" type="number" step="0.1" readonly/>
<button data-numinput="-"> - </button>
<button data-numinput="+"> + </button>

Related

Listen for blank inputs and add a "disabled" attribute to a button until an input is noticed

I have a user input field that, if blank, I would like the submit button to be disabled until a key press in the input box is noticed. But, if they blank out the input box, then the button is disabled again.
So, I'd like to add the "disabled" attribute to this input button:
<input type="submit" id="mapOneSubmit" value="Submit" [add attribute "disabled" here]>
The input is from this HTML here:
<input type="text" id="mapOneUserInput" onkeypress="return isNumberKey(event)" oninput="validate(this)">
Note: I have onkeypress and oninput validation to prevent non-number inputs and allow only 2 decimal places.
I assume my JS would look like this to add the disabled attribute:
document.getElementById("mapOneSubmit").setAttribute("disabled");
My problem is, I can't find what event listener listens for "blank" inputs? Can you help me with that?
Thanks kindly!
Check this one as well.
function checkvalid(el)
{
//e.g i am preventing user here to input only upto 5 characters
//you can put your own validation logic here
if(el.value.length===0 || el.value.length>5)
document.getElementById("mapOneSubmit").setAttribute("disabled","disabled");
else
document.getElementById("mapOneSubmit").removeAttribute('disabled');
}
<input type='text' id ='inp' onkeyup='checkvalid(this)'>
<button id='mapOneSubmit' disabled>
Submit
</button>
Yet using the input event:
<input type="text" id="mapOneUserInput" onkeypress="return isNumberKey(event)" oninput="validate(this);updateSubmit(this.value)">
Then in js
function updateSubmit(val) {
if (val.trim() == '') {
document.getElementById('mapOneSubmit').disabled = true;
}
else {
document.getElementById('mapOneSubmit').disabled = false;
}
}
You can find the below code to find the blank inputs
function isNumberKey(event) {
console.log(event.which)
}
var value;
function validate(target) {
console.log(target);
}
<form>
<input type="text" id="mapOneUserInput" onkeypress="return isNumberKey(event)" oninput="validate(this)">
<input type="submit" id="mapOneSubmit" value="Submit" [add attribute "disabled" here]>
</form>
You can you set the enable/disable inside validate function.
function validate(elem) {
//validation here
//code to disable/enable the button
document.getElementById("mapOneSubmit").disabled = elem.value.length === 0;
}
Set the button disable on load by adding disabled property
<input type="submit" id="mapOneSubmit" value="Submit" disabled>
On your validate function just check if value of input field is blank then enable/disable the button
function validate(input){
input.disabled = input.value === "" ;
}
My problem is, I can't find what event listener listens for "blank" inputs?
You can disable the submit button at render, after that you can use the input event to determine whether the input value is empty or not. From there, you can set state of the submit button.
document.addEventListener('DOMContentLoaded', () => {
const textInput = document.getElementById('mapOneUserInput');
textInput.addEventListener('input', handleTextInput, false);
textInput.addEventListener('keydown', validateInput, false);
});
function handleTextInput(event) {
const { value } = event.target;
if (value) {
enableSubmitButton(true);
} else {
enableSubmitButton(false);
}
}
// Refer to https://stackoverflow.com/a/46203928/7583537
function validateInput(event) {
const regex = /^\d*(\.\d{0,2})?$/g;
const prevVal = event.target.value;
const input = this;
setTimeout(function() {
var nextVal = event.target.value;
if (!regex.test(nextVal)) {
input.value = prevVal;
}
}, 0);
}
function enableSubmitButton(isEnable) {
const button = document.getElementById('mapOneSubmit');
if (isEnable) {
button.removeAttribute('disabled');
} else {
button.setAttribute('disabled', '');
}
}
<input type="number" value="" id="mapOneUserInput">
<!-- Note that the input blank at render so we disable submit button -->
<input type="submit" id="mapOneSubmit" value="Submit" disabled>

HTML attribute which excludes this value

" <input type="number" min="1" max="100"> *
...
I did not know how to exclude 0, so I set the minimum value to 1, Please help)
you cannot exclude via html syntax, you'd need javascript for that. the min value=1 might be the only way via html only.
You can use jquery like that:
$('input').keypress(function(e){
if (this.value.length == 0 && e.which == 48 ){
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" min="1" max="100">
As I understood from you question you want to exclude zero, which means all other numbers (< 100) are accepted
try this code: it accepts the negative numbers + positive numbers > 0 and =< 100
const input = document.querySelector("input")
input.addEventListener('change', function(e) {
if ( e.target.value === "0" ) {
input.value = 1
}
})
<input type="number" max="100"/>

Javascript conditional hiding and showing

Hello guys I'm confused with javascript code, I want a program that gets the input from the user, and if that input matches a specific value like 1234 I want it to hide part of the form. E.g.
var x=document.getElementById('pin').value;
function hidden() {
if (x.value=1234){
document.getElementById('pin').style.display="none";
}
}
<input type="number" name="pin" placeholder="Please Enter Your Pin" id="pin">
<button onclick="hidden()">Enter</button>
var x=document.getElementById('pin');
function checkPin() {
if (x.value == "1234"){
x.style.display="none";
}
}
<input type="number" name="pin" placeholder="Please Enter Your Pin" id="pin" />
<button onclick="checkPin()">Enter</button>
The value is not a native number, but a string, and you're assigning in the conditional check. Instead of '=' use '==' or '==='.
Try this:
function hidden() {
var x = document.getElementById('pin').value;
if (x === '1234'){
document.getElementById('pin').style.display = 'none';
}
}

How to do onkeypress in angular 4

I am trying to implement a input tag that only allows numbers to be put in.
One way that I found work is the following
<input name="num"
type="number"
pattern="[0-9]*"
placeholder="Enter new PIN"
onkeypress="return event.charCode >= 48 && event.charCode <= 57"
title="Numbers only">
But I would like to change onkeypress for an angular function. Is there anything that can work similar?
I have tried (keyup), and (change) but neither work the same. They allow the key to be pressed then remove the number.
<input (keyup)="checkPin($event)"
type="number"
pattern="[0-9]*"
placeholder="Enter new PIN"
inputmode="numeric"
style="-webkit-text-security: disc;"></input>
Here is the TS function checkPin
checkPin($event: KeyboardEvent) {
console.log($event)
let value = (<HTMLInputElement>event.target).value;
if ($event.target) {
if (value == "") {
value = value.slice(0, 0);
}
if (value.length > 4) {
value = value.slice(0, 4)
}
(<HTMLInputElement>event.target).value = value.replace(/\D/g, '');
}
}
TS method:
keyPress(event: KeyboardEvent) {
const pattern = /[0-9]/;
const inputChar = String.fromCharCode(event.charCode);
if (!pattern.test(inputChar)) {
// invalid character, prevent input
event.preventDefault();
}
}
HTML:
<input (keypress)="keyPress($event)"
type="number"
pattern="[0-9]*"
placeholder="Enter new PIN"
inputmode="numeric"
style="-webkit-text-security: disc;"></input>
Here the pattern in html is not needed because you are restricted to type another character than 0-9.
Good luck!
For anyone else looking for another way of determining if a specific key is pressed (like the space key), you can use:
grabText(event){
if(event.code === 'Space'){
console.log('PRESSED SPACE');
...
}
}
We should use KeyboardEvent instead of event as a type of the input parameter of keyPress
To make a input field number only, you can do this. So you can use onkeypress for another function.
<input type="text"
onkeydown="javascript: return event.keyCode === 8 ||
event.keyCode === 46 ?
true : !isNaN(Number(event.key))"/>

React Refs' value not showing

This is a very simple example. I have a form and I need the value of a hidden field so I need to use ref:
<form>
<input ref="num" type="hidden" name="amount" value="99"/>
</form>
var number = this.refs.num.value;
console.log(number); // nothing
console.log(this.refs.num); // shows the field
How to get the value with ref?
I think you get value, before rendering, try this:
handleSubmit(e) {
if (e) {
e.preventDefault();
}
var value = this.refs.num.value;
console.log(value);
}
render() {
console.log(this.refs.num ? this.refs.num.value : '');
return (
<form>
<input ref="num" type="hidden" name="amount" value="99" />
<a onClick={this.handleSubmit.bind(this)}>submit</a>
</form>
);
}
output would be empty string at first and 99 after render:

Categories

Resources