user3256131
user3256131

Reputation: 21

prevent cut copy paste in html5 application

I don't want to allow user to cut copy paste in textbox I have tried following code but it is not even bind to that element:

$(document).ready(function(){
$("userName").on("cut copy paste",function(e){
e.preventDefault();
});
});

Upvotes: 2

Views: 2853

Answers (3)

thomaswardiii
thomaswardiii

Reputation: 3

So the code here looks mostly sane. Using an example from this blog post I made this jsFiddle and it definitely works, including on my Android device.

What I think is being overlooked here is two things:

  • A snippet of the form's HTML
  • How jQuery's selectors actually work

IDs

IDs are meant to be unique to all elements on the page. One and only one element will be selected. The way to select this is: $('#id_name'). An example of HTML with an ID:

<input name="field_name" id="id_name">

Classes

Classes are used by both CSS and selectors. They can be used on one or more elements. All elements with this class are selected. The way to select this is: $('.class_name'). An example of HTML with a class:

<input name="field_name" class="class_name">

Name

Names are generally used by forms to pass information back to the server once submitted; they are less used for selectors than IDs or classes. They can be used on one or more elements. All elements with this class are selected. The way to select this is: $('[name="field_name"]'). An example of HTML with just a name:

<input name="field_name">

Summary

What I believe is actually going on is that the HTML for the field does not contain an ID and only a name. In addition, the selector as written is most likely incorrect. This selector would be designed to select a userName element Such as:

<userName foo="bar">This is a custom element</userName>

Most likely this is not what you want, and you most likely are missing the correct type of selector and perhaps the correct attributes associated to use this selector

Upvotes: 0

kamesh
kamesh

Reputation: 2424

Change the selector identity if it is id means use

$(document).ready(function(){
$("#userName").bind("cut copy paste",function(e){
e.preventDefault();
});
});

or if it is class

 $(document).ready(function(){
    $(".userName").bind("cut copy paste",function(e){
    e.preventDefault();
    });
    });

Upvotes: 1

monu
monu

Reputation: 370

$(document).ready(function(){
  $('#userName').bind("cut copy paste",function(e) {
  e.preventDefault();
 });
});

Upvotes: 2

Related Questions