Reputation: 1828
I want to check on click if the input field #plz-input
contains one of the two words: "red" or "green".
I tried .contains()
but it does only work with the first word.
$('#submit').click(function() {
if( $("#plz-input").contains('red green')) {
alert("Wrong Value ...");
} else {
alert("Right Value!");
}
return false;
});
Upvotes: 0
Views: 2071
Reputation: 76547
Consider a Regular Expression
You could easily accomplish this with a simple regular expression via the RegExp.test()
function. Just separate your your individual terms with a pipe as seen below :
var colors = new RegExp('red|green|purple|...');
Then just call the test()
function, which will indicate if any of those terms are found within your string as seen below:
// Define an expression of words to check for
var colors = new RegExp('red|green');
// Check if any of the words is contained within your element
if(colors.test($('#plz-input').val()){
alert('Wrong Value ...');
} else {
alert('Right Value!');
}
Example
<input id='colors' onkeyup='checkForColors(this);' /> <span id='result'></span>
<script>
var result = document.querySelector('#result');
function checkForColors(element){
var colors = new RegExp('red|green');
result.innerText = colors.test(element.value) ? 'Incorrect!' : 'Correct!';
}
</script>
Upvotes: 3