Need to Create an input element that takes only letters from a-z, A-Z and space

348 views Asked by At

Create an input element on the page with a placeholder” enter your name” and an H2 heading on the page inside HTML. The purpose of this input element is to enter a user’s name so it should only input. letters from a-z, A-Z and space (all other characters should not be detected). Whenever the user inputs their name, their input should be dynamically visible inside the heading. [Please note that no other character apart from the allowed characters should be visible in the heading]

HTML CODE Inside body

<h2></h2>
    <input placeholder="Enter your name" />

JavaScript Code

let input = document.querySelector("input");
let h2 = document.querySelector("h2");

input.addEventListener("input",function(){
    console.log(input.value);
    h2.innerText=input.value;
});
2

There are 2 answers

0
Alexander Nenashev On

Use beforeinput event and test whether Event::data matches your allowed characters. If not, call Event::preventDefault() to cancel the changing of the input:

let input = document.querySelector("input");

input.addEventListener("beforeinput", e => /^[A-Za-z ]+$/.test(e.data) || e.preventDefault());
<input placeholder="Enter your name" />

1
Harshit Kumar Jain On
let inpt = document.querySelector("input");
let h2 = document.querySelector("h2");

inpt.addEventListener("input",function(){
    let username = inpt.value;
h2.innerText = username.replace(/[^a-zA-Z\s]/g, '');
})
<h2>....</h2>
 <br>
 <input type="text" placeholder="enter your name">