admin管理员组

文章数量:1402857

I am trying to do a string parison like so in JQuery

$('#select_directory_type').on('change', function() {
     window.alert($(this).val()); // I can see the selection is "SOMETHING"
     if( "SOMETHING" === $(this).val() ){
         // Never gets executed even when the selection is "SOMETHING".
     } });

Another question is, what is the difference between

$this.val()
and 
$(this).val()

Thanks!

I am trying to do a string parison like so in JQuery

$('#select_directory_type').on('change', function() {
     window.alert($(this).val()); // I can see the selection is "SOMETHING"
     if( "SOMETHING" === $(this).val() ){
         // Never gets executed even when the selection is "SOMETHING".
     } });

Another question is, what is the difference between

$this.val()
and 
$(this).val()

Thanks!

Share Improve this question edited Aug 4, 2017 at 18:26 Barmar 784k57 gold badges548 silver badges660 bronze badges asked Aug 4, 2017 at 17:50 N0000BN0000B 4492 gold badges7 silver badges18 bronze badges 4
  • 1 This is a searchable index of questions and answers. Please ask one question at a time. – Bill the Lizard Commented Aug 4, 2017 at 17:51
  • 2 $this is not defined. If you are talking about the DOM syntax, you want this.value otherwise you need to explicitly defined var $this = $(this); – Sterling Archer Commented Aug 4, 2017 at 17:52
  • Please, put an example for your broken code. – Mohamed Abbas Commented Aug 4, 2017 at 17:54
  • Post the HTML of the #select_directory_type element. – Barmar Commented Aug 4, 2017 at 18:26
Add a ment  | 

3 Answers 3

Reset to default 3

In reverse order $(this).val() says, give jquery (represented by a $) the value this, and then call the function .val() on the return of that function. $this.val() is saying, call the function .val() on the variable $this, which i suspect you haven't defined.

It looks like your snippet of code should work, but === checks for exact string equality, I'd highly suggest you inspect your string in console using console.log, to verify it doesn't have any trailing whitespaces or similar. Replace your alert with console.log(), and look in the developer console (ctrl-shift-I on chrome). you could also

 console.log( "SOMETHING" === $(this).val()) 

to see if your issue is actually the parison. Its most likely whitespace related though.

There might be extra whitespace on either end of the string. Try:

if( "SOMETHING" === $(this).val().trim() )

jQuery syntax is generally $(selector). If your case this is your selector so $(this) would be the correct syntax.

本文标签: javascriptjQuery compare string to input valueStack Overflow