简体   繁体   中英

I want to hide div if html data is empty, I want to show if it is not. HTML JavaScript

When I select from list, I am getting stock data from controller and display on the page. But, I want to hide this "We have products in stock" writing firstly, I want to show "We have 26 products in stock" after I select from list and the value come from controller. Either I could show complete writing or I could hide complete writing. I could not show it depends on stock value.

Create.cshtml

 <div id="hide">
            <label>We have <text id="stock"></text> products in stock</label>
        </div>
 $.ajax({
            success: function (data) {
                $("#stock").html(data);
                }
        });
<script>
        if ($('#stock').val().length == null) {
            $('#hide').hide();
        }
        else {
            $('#hide').show();
        }
    </script>

My script codes are wrong.

You can achieve this by following code.

 <div id="hide">
            <label>We have <text id="stock"></text> products in stock</label>
        </div>

<script>
         $.ajax({
            success: function (data) {
               if(data){
                     $("#stock").html(data);
               }
               else{
                   $('#hide').hide();
               }
            }

        });
    </script>

The thing is, you need to check data is empty or not. So when the ajax is completed, you should check the data. I don't know the exact model what's you returning but the logic should be like this.

将if($('#stock')。val()。length == null){更改为if(!$。trim($('#stock')。html()).length){

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM