javascriptjqueryhtmldynamicprofanity

jQuery Profanity filter not updating while typing


I would like to dynamically filter bad words using this profanity filter. The api will change "ass" to "***" in the given example, only if the text was there before page load. I would like it to change recognized bad words as they are typed, to prevent someone from sending a naughty messages through a my contact form.

Here is what i've got so far:

   <div id="msg">
      <textarea type="text" onkeypress="badFilter()" id="mess_box" name="cf_message" style="height:150px;" maxlength="500" placeholder="Message" ></textarea>
   </div>

   <script>
      function badFilter() {
      $typedText = $('#mess_box').val();
      $typedText.profanityFilter({
         customSwears: ['ass']
      });
      }
   </script>

I would think that the 'onkeypress' attribute would force the script to check for updated textarea values, but that is not the case.

Help appreciated!


Solution

  • You are assigning the filtered value to a variable, and then you are not using it.

    function badFilter() {
     $typedText = $('#mess_box').val();
     $typedText.profanityFilter({
      customSwears: ['ass']
     });
     $('#mess_box').val($typedText);
    }
    

    the last line will apply text back to the input box.

    The problem is that you are changing the value of the input element while the user is typing. This way, there will be glitches if the user types in the middle of the text (not at the end).

    You could create a system of two input controls (one hidden, one visible) where user types into one (hidden) and censored text appears in the visible one. When user positions cursor in the visible control, you would position it on the same character in the invisible one. Updating the text of the visible control will not glitch while the user is writing.

    This will work only if profanityFilter can work with string object. If not, the correct way to initialise it would be

    $('#mess_box').profanityFilter({
     customSwears: ['ass']
    });