0

I'm trying to create something in my website using javascript which'll just alert when the value in textarea typed is suppose "Hello", this should only be applicable for the word after space.

For example:

<textarea id="txtar" cols="30" rows="10"></textarea>

so when I whenever enter Hello then it'll alert

NOTE: typing "hello" and then "hello" again after spacing must also show alert but the problem coming is that it's taking value as hello hello and hence not showing any results.

Andy
  • 61,948
  • 13
  • 68
  • 95
Lucy
  • 3
  • 1
  • 3

2 Answers2

0

You're going to want to attach a listener to the text-box:

Like this: Best way to track onchange as-you-type in input type="text"?

If I understand the problem correclty you want to alert when the phrase, in this case, Hello, is added to the input string and is not the same as a previous entry.

const textBox = document.getElementById('txtar');

let lastAlert = ""

const inputHandler = function(e) {
  const textValue = e.target.value;
  const splitTextValue = e.target.value.split(" ")  // split the string by spaces
  const lastWord = splitTextValue[splitTextValue.length-1]
  if (lastWord === "Hello" && lastAlert !== textValue) {
    alert("Alert Something")
    lastAlert = textValue;
  }
}

textBox.addEventListener('input', inputHandler);
textBox.addEventListener('propertychange', inputHandler); // for IE8
// Firefox/Edge18-/IE9+ don’t fire on <select><optio

This is completely untested, but, in my head, this works.

Ollie Pugh
  • 373
  • 2
  • 15
  • Worth noting, this will not really work if the users starts to modify the middle of the string... it will only work if the user is modifying the end of the input box – Ollie Pugh Sep 10 '22 at 13:42
  • It do really worked atleast for what I wanted, Thanks. – Lucy Sep 11 '22 at 09:32
0

Using regex you can try this

    <textarea id="txtar" ></textarea>

    let lastLength = 0;
    document.getElementById('txtar').addEventListener('input', (event)=>{
    let pattern = /\sHello/ig;
    let result = event.target.value.match(pattern);
    if(result!=null)
    if(result.length>lastLength ){
    alert("Hello is typed");
    lastLength=result.length;
    }
    })

Hope it helps