How can you check to see whether the returned results contain a specific value?
$(function () {
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
//here i wanna check if the result return contains value "test"
//i tried the following..
if($(result).contains("test")){
//do something but this doesn't seem to work ...
}
}
},
});
});
});
if(result.indexOf("test") > -1)
Since this still gets up votes I'll edit in a more modern answer.
With es6 we can now use some more advanced array methods.
result.includes("test")
which will return a true or false.
If your array contains objects instead of string you can use
result.some(r => r.name === 'test')
which will return true if an object in the array has the name test.
The jQuery object does not have a contains
method. If you are expecting the returned result to be a string, you can check if your substring is contained within it:
if ( result.indexOf("test") > -1 ) {
//do something
}
If your result is JSON, and you're checking for a top-level property, you can do:
if ( result.hasOwnProperty("test") ) {
//do something
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With