Search code examples
javascriptjqueryhtmltextareastartswith

Textarea startswith function not working


I am trying to apply starts with function on textarea, but obviously I am doing something wrong. I don't understand javascript, so I am sorry for obvious mistakes or problems. At least I tried what seemed logical to me... Fiddle here: http://jsfiddle.net/SVxbW/235/

HTML:

$("textarea").bind(function () {
  if ($(this).startsWith("Hello") {
      $(".kuk").show();
  }
  else {
   $(".kuk").hide();
  }
}); 
.kuk {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<textarea></textarea>
<button class="kuk">Clear</button>

And what if someone pastes the text "Hello" with right click of mouse? How to recognize that action too?


Solution

  • You need to get the val() then use startsWith(). Additionally you need to bind proper event handler. Here I have used keyup

    $("textarea").on('keyup', function() {
        if ($(this).val().startsWith("Hello")) {
            $(".kuk").show();
        } else {
            $(".kuk").hide();
        }
    });
    

    Updated Fiddle