Disable Paste action using Javascript (without include Jquery)

Viewed 492

I have a text box for the login mobile number, I have to disable the paste action

Am working in ReactJs, The code that I used is Mention below.

<input
 type="text"
 name="userName"
 placeholder="Mobile number"
 onChange={e => this.onChangeNumber(e)}
 value={this.state.userName}                      
 maxLength="10"
 autoFocus
 autoComplete="off"
/>

I want to disable the paste action using the JS code without using jquery and any other packages. Anyone help me to complete this.

Thanks in Advance.

4 Answers

If you are using the reactjs, you can directly use the onPaste event in the input tag as given below. So it will restrict the paste action.

     <input
     type="text"
     name="userName"
     placeholder="Mobile number"
     onChange={e => this.onChangeNumber(e)}
     onPaste={e => {e.preventDefault()}}
     value={this.state.userName}                      
     maxLength="10"
     autoFocus
     autoComplete="off"
    />

If you want use the js, you can use the following code in your function. So that the paste action will get prevented.

    onChangeNumber =()=>{
       document.getElementByName('userName').onpaste=function(e){
         e.preventDefault();
       }
     }

One of the many ways to do this is like



  useEffect(()=>{
    document.getElementById('ipt').onpaste=function(e){
      e.preventDefault();
    }
  },[])


  return (
    <div className="App">

      <input
          type="text"
          name="userName"
          placeholder="Mobile number"
          id='ipt' 
          autoFocus
          autoComplete="off"
        />
    </div>
  );
}

Why useEffect used ? So, that the DOM element input has initialised and does not return NULL when we document.getElementById it.

NOTE: It is generally not advisable to restrict pasting to an input field. It is annoying and affects the User Experience.

PS: I am not exactly sure why refs dont work with onpaste. maybe that would be a better REACTish way of doing it.

<input
 type="text"
 name="userName"
 placeholder="Mobile number"
 onChange={e => this.onChangeNumber(e)}
 onPaste={e => {e.preventDefault()}}
 value={this.state.userName}                      
 maxLength="10"
 autoFocus
 autoComplete="off"
/>

Simply preventing default action onPaste would do needful.

<input type="text" class="word"> //html code
let box = document.querySelector(".word");// javacript method
//Disable Paste Event
box.onpaste = function () {
    return false;
}
Related