0

I have a textarea, and I need to check if this textarea.value contains a string from a string array. Every onkeyup in textarea I call this script. I tried this code, but something went wrong. "@" is ok, but "apple" and "orange" is not. Please help me! Thanks!

var str = document.getElementById("messageArea").value;

var arr = ["@", "apple", "orange"];

for (var i = arr.length - 1; i >= 0; --i) {
    if (str.indexOf(arr[i]) != -1) {
      alert('contains');
   } else {
        alert('not contains');
    }
}
12
  • Can you provide a complete example? (input, expected output...) Commented Jan 31, 2016 at 11:43
  • Sorry, I forgot this: every onkeyup in textarea i call this script Commented Jan 31, 2016 at 11:45
  • What is the value of str? your problem is not reproducible... The code seems fine Commented Jan 31, 2016 at 11:47
  • jsbin.com/vavakoluhe/1/edit?html,js,output . code seems fine Commented Jan 31, 2016 at 11:49
  • in my code I turn on or off a button. So when I typing, and I type @, my button is off, it is ok. But when i typing, and i type orange nothing happened. Commented Jan 31, 2016 at 11:51

2 Answers 2

1

Break the loop when the message contains the substring.

$("#messageArea").on("keyup",function(e){
var str = document.getElementById("messageArea").value;

var arr = ["@", "apple", "orange"];

for (var i = arr.length - 1; i >= 0; --i) {
    if (str.indexOf(arr[i]) != -1) {
      $('#messageBtn').prop('disabled',false);
break;
   } else {
        $('#messageBtn').prop('disabled',true);
    }
}
  });
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <textarea type="text" id="messageArea"></textarea>
  <button disabled id="messageBtn">submit</button>

</body>
</html>

Sign up to request clarification or add additional context in comments.

Comments

0
var str = "@ apple orange"; //document.getElementById("messageArea").value;

var arr = ["@", "apple", "orange"];


str = str.trim();

var parts = str.split(" "); // split textarea string by space into another array

for (var part in  parts) { // iterate one every part and check it with your arr variable
  if ( arr.indexOf(parts[part]) != -1 ) {
    alert("found: " + parts[part] );
  } else {
    alert("not contains " + parts[part]);
  }
}

you will get alerts for all 3 elements in the str variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.