Search code examples
javascriptruby-on-railssimple-form

Disable copy/past functionality in simple_form


I'm trying to disable the copy/paste functionality in the input field of a simple_form. I understand this has been asked before outside of a simple_form context. I added a class to the form itself following the ideas from this post, and used that class within a function in application.js. This is currently not producing the desired functionality--is there an idiosyncratic way to do this in simple_form?

(I understand it's not recommended to tamper with default browser functionality, but the action of copying 'by hand' would jibe with what I'm trying to achieve with my app).

In the view:

<%= simple_form_for @word, url: lesson_word_exposition_path(current_lesson, @word.word), html: { class: "disablecopypaste"}, method: :patch do |f| %>
  <%= f.input :term_given_by_student, label: "Enter the term exactly as above:" %><br>
  <%= f.button :submit, class: 'btn btn-primary' %>
<% end %>

From application.js:

$(document).ready(function () {
    $('input.disablecopypaste').bind('copy paste', function (e) {
       e.preventDefault();
    });
  });

Solution

  • You could try using the user-select css property.

    .unselectable : {
      -webkit-user-select: none;  
      -moz-user-select: none;    
      -ms-user-select: none;      
      user-select: none;          
    }
    
    
    $(document).ready(function () {
        $('input.disablecopypaste').toggleClass('unselectable')
      });