1
votes

I have to restrict a input field to accept only numbers. We are not using "lightning-input". How to use below js function in Lightning web component?

function isNumber(evt) {
        var iKeyCode = (evt.which) ? evt.which : evt.keyCode
        if (iKeyCode != 46 && iKeyCode > 31 && (iKeyCode < 48 || iKeyCode > 57))
            return false;     

return true; }

2

2 Answers

0
votes

See below:

.html file

<lightning-card>
    <div class="slds-m-around_medium">
        <input type="number" onkeypress={handleKeyPress} pattern="[0-9]" class="slds-input" />
    </div>
</lightning-card>

.js file

handleKeyPress(event) {
    let input_number = event.target.value;
    console.log('Number: '+input_number); 
}    

Results/output Results/output

0
votes

I believe it allows "e" & "k" as valid numbers,

here's what I did

.html file

<input class="numfield" onkeydown={onlyNumericAllowed} type="number" >

.js file

onlyNumericAllowed(event) {
    if(event.keyCode === 69){
        event.preventDefault();
    }
    const value = event.target.value;
    console.log(event.charCode);
    if (value && (!/^[0-9]+$/.test(value) || event.keyCode == 0)) {
        this.template.querySelector('.numfield').value = value.replace(/\D/g, '');
    }
}