Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
46
rated 0 times [  50] [ 4]  / answers: 1 / hits: 18326  / 7 Years ago, fri, august 4, 2017, 12:00:00

I am trying to do a string comparison 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!


More From » jquery

 Answers
16

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 comparison. Its most likely whitespace related though.


[#56866] Wednesday, August 2, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kevonmoisesf

Total Points: 693
Total Questions: 101
Total Answers: 128

Location: Reunion
Member since Mon, Dec 28, 2020
3 Years ago
;