简体   繁体   中英

how could i know the value of input in textarea HTML only of the word written after spacing?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM