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 wantthis.value
otherwise you need to explicitly definedvar $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
3 Answers
Reset to default 3In 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
版权声明:本文标题:javascript - jQuery compare string to input value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744330402a2600936.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论