What jQuery do I need to hide a div class if an input value is empty?

好久不见. 提交于 2020-01-06 06:59:15

问题


In my options panel I have a section where the user can enter their Twitter username. Currently if the value for that field is empty, the Twitter icon disappears on my website, which is good as it means the div class has been successfully hidden. However, when I enter a username in the field, the div class still stays hidden.

This is the jQuery I have at the moment:

<script type="text/javascript">
$(document).ready(function() {
if($('mytheme_twitter:empty')){$('.twitter').hide();}   
});
</script>

I think something must be missing from it. Do I need to add another function? If so, where do I put it? I'm a bit of a jQuery noob.


回答1:


Firstly :empty is the wrong selector for this use case.

:empty Select all elements that have no children (including text nodes

Change you logic to check if the value of the imput is empty.

if($('.mytheme_twitter').val() === '' ){$('.twitter').hide();} 

You need to write up a change event to handle that case..

$('mytheme_twitter') has to be   $('#mytheme_twitter')  If ID OR $('.mytheme_twitter') If Class

//

 <script type="text/javascript">
    $(document).ready(function() {

        if($('.mytheme_twitter').val() == '' ){$('.twitter').hide();}  

        $('.mytheme_twitter').on('change' , function() {

             if( this.value != ''){

                   $('.twitter').show(); 
              }
              else{
                   $('.twitter').hide(); 
             }
        });
      });
    </script>



回答2:


I would do something like this:

<script type="text/javascript">
    $(document).ready(function () {
        var twitter = $(".twitterTextBox").val();
        if(twitter == "") {
            $(".twitterIcon").hide();
        } else {
            $(".twitterIcon").show();
        }
    });
</script>

This only checks the input when the page loads. If you want the Twitter icon to show once they type something in the text box, then you'll have to add an event listener such as onkeyup.

Hope this helps.



来源:https://stackoverflow.com/questions/12785622/what-jquery-do-i-need-to-hide-a-div-class-if-an-input-value-is-empty

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!