21

I want to know if the textarea value contains a certain word. This is not working for me.

var value = $('#embedModal textarea').val();
if($(value).contains('iframe')){...
Hussein
  • 42,480
  • 25
  • 113
  • 143

5 Answers5

33

Try javascript

if (value.indexOf('iframe') >= 0) {

JQuery contains is for DOM elements, not strings.

Nikita Rybak
  • 67,365
  • 22
  • 157
  • 181
  • This won't work in all IE browsers. https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf – Jason Foglia May 05 '13 at 19:54
  • @JasonFoglia That is the documentation for the array's indexOf function, not [string's indexOf](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/indexOf). – Nikita Rybak May 05 '13 at 22:51
4

Try doing it like this:

$('#embedModal textarea:contains("iframe")').each(function() {
  //Do something
});

edit

Example

Aaron Hathaway
  • 4,280
  • 2
  • 19
  • 17
1

this works:

$.contains( document.documentElement, document.body ); // true

var babyEl = $('div#id');
var daddyEl = $('div#ID');

if($.contains(babyEl, daddyEl)) {
    //do fun stuff
}
CSchulz
  • 10,882
  • 11
  • 60
  • 114
bobr37
  • 11
  • 2
0

Try following code.....

code:

             <textarea rows="4" cols="9">Something iframe</textarea>
             <textarea rows="4" cols="9">Something</textarea>

               var obj=$("textarea:contains('iframe')");

                   if(obj){

                            obj.css("background-color", "red");

                         }
  • -1 because this was already suggested in [this answer](http://stackoverflow.com/a/4939095/447356) plus that `if` condition will always be true so it's pointless. jQuery selector will always return jQuery collection object, if you want to check it contains anything you should check its `length` property. See [this fiddle](http://jsfiddle.net/5edsr/) vs. [this one](http://jsfiddle.net/5edsr/1/). – Shadow The GPT Wizard Dec 12 '12 at 12:13
  • yes, jQuery selector will always return jQuery collection object but condition will be true at that point when any textarea contain iframe key world otherwise will be false .... – Ram Lakhan Yadav Dec 12 '12 at 12:35
  • No, it will never be false because jQuery collection is an object. – Shadow The GPT Wizard Dec 12 '12 at 12:53
0

You can do this as well:

if($('#embedModal textarea:contains("iframe")').length > 0){
    //TODO: do stuff
}
Jason Foglia
  • 2,414
  • 3
  • 27
  • 48