I’m tryng to achieve if user input on id “comments” is word that is present in my FilterWord’s array then user will be redirected to an url. If input is anything else, then user will be redirected to another url.
Checking has to start after user click on submit.
var buttonPress = function () { var com = document.getElementById('comments'); var filterWords = ["apple", "yellow", "melon", "blue", "red"]; // "i" is to ignore case and "g" for global var rgx = new RegExp("("+filterWords.join("|")+")", "gi"); if (com.value == rgx) { window.location.href = "http://www.google.com"; } else { window.location.href = "http://www.bing.com"; } };
<form name="words" method="post" action="" onsubmit="return buttonPress();"> <textarea name="comments" id="comments" rows="5" cols="50"></textarea> <br /> <input id="formSub" type="submit" value="Submit!" /> </form>
Advertisement
Answer
Just validate with some.
var buttonPress = function () { var com = document.getElementById('comments'); var filterWords = ["apple", "yellow", "melon", "blue", "red"]; var exists = filterWords.some(word => word == com.value); if (exists) { window.location.href = "http://www.google.com"; } else { window.location.href = "http://www.bing.com"; } return false; };