-1

I got a website need to check user input value is contain porn site URL or not, so I can do reject the input

Using: Chrome

$porn = [''];
$.getJSON('https://cdn.rawgit.com/aredo/porn-site-list/master/sites.json',function(data){
  $(data).each(function(index,value){
    $pornlist = value.host;
    $porn.push($pornlist);
  });

$('.urlinput').on('input',function(){
  $text = $(this).val();

  if (jQuery.inArray($porn,$text) != -1) {
    //Porn site not allow
    console.log('in webiste')
  } else {

    //Not porn site allow
      console.log('not in website')
  }

  });

});
Felix Fong
  • 969
  • 1
  • 8
  • 21

5 Answers5

2

jQuery.inArray($text, $site) >-1 is the key. When no match found -1 will be returned instead of the index.

Demo: http://codepen.io/8odoros/pen/aZJPgV

$site = ['google','facebook','twitter'];

//$('.urlinput').on('input',function(){
  //$text = $(this).val();
  $text = 'facebook';

  if (jQuery.inArray($text, $site) >-1) {
    console.log('in webiste')
  }else {
    console.log('not in website')
  }

// });
Theodore K.
  • 5,058
  • 4
  • 30
  • 46
2

Try:

$site = ['google','facebook','twitter'];
$text = 'facesbook';
if (jQuery.inArray($text, $site)  !== -1 ) {
    console.log('in webiste')
}else {
    console.log('not in website')
}
Jayesh Chitroda
  • 4,987
  • 13
  • 18
1

Your issue is comparing the result to true. $.inArray (as with indexOf) returns an integer value. -1 if the element is not found and it's index in the array if it is found. Therefore your logic would return true when -1 or > 0 and false if the element is found at index 0.

To fix this, compare to -1 instead:

if (jQuery.inArray($text, $site) != -1) {
    console.log('in webiste')
} else {
    console.log('not in website')
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

$.inArray($string, $array) returns the index of the element in the array, if it exists in the array. If the element was not found, -1 will be returned

$site = ['google', 'facebook', 'twitter'];
$text = 'facebook';
if ($.inArray($text, $site) !== -1) {
  console.log('in webiste')
} else {
  $.log('not in website')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
zakhefron
  • 1,403
  • 1
  • 9
  • 13
-1

You need to run the loop and test the value

for ( var i = 0; i < $site.length; i++){
 if ( $site[i] == $text) {
    console.log('in webiste')
  }else {
    console.log('not in website')
  }
}
Theodore K.
  • 5,058
  • 4
  • 30
  • 46
Akash
  • 377
  • 6
  • 17