-1

I have a div which has a dynamic value. When #div1 is empty, I would like to show a simple value "0".

This is what I have so far:

<script language="javascript"> 
if ($('#div1').is(':empty')){
   //and here I don't know to return value 0 as text
}
</script>
Glenn
  • 8,932
  • 2
  • 41
  • 54
infobz
  • 1
  • 1
  • You want a string "0"? How is this 0 going to be used? – victor Nov 11 '15 at 21:22
  • 1
    Returning it is easy: `return '0'`. The hard part is figuring out what exactly you're trying to do with that returned text. Unfortunately your current code won't do anything with it. – Justin Niessner Nov 11 '15 at 21:22
  • I assume that by "return 0" you mean "show 0"? If so, where do you want to show it? – JJJ Nov 11 '15 at 21:23
  • Yes show 0, for example if div is empty show "some text", in my case 0. – infobz Nov 11 '15 at 21:36
  • Where do you want to show it? – JJJ Nov 11 '15 at 21:36
  • in the same div (I got it with some research and solve it) – infobz Nov 11 '15 at 21:55
  • You seem to be using jQuery, so I recommend to read the jQuery tutorial first. It should cover everything you need to know for this: http://learn.jquery.com/using-jquery-core/ . – Felix Kling Nov 11 '15 at 21:56
  • My answer for me was found here and now it works nice and smooth..https://api.jquery.com/empty-selector/. Thanks all for answers – infobz Nov 11 '15 at 21:59

3 Answers3

1

Maybe like this:

if ($('#div1').is(':empty')) {
 $('#div1').text("0");
}
Ikbel
  • 7,721
  • 3
  • 34
  • 45
0

If you want the div to contain the text "0", just do $('#div1').html("0");

victor
  • 1,532
  • 1
  • 13
  • 32
-1

Or maybe like this:

if ($('#div1').is(':empty')) {
 $('#div1')[0].innerHTML = '0'; // u can add more DOM elements in this way
}

For example:

    var moreDom = '<div id="someDiv"><p>some text in div<p></div>' + 
                    '<div id="someDiv2"><p>some text in div2<p></div>';
    $('#div1')[0].innerHTML = moreDom;
  • This won't work. jQuery objects don't have an `innerHTML` property (granted, this might not be jQuery, but it very much looks like it). – Felix Kling Nov 11 '15 at 21:57
  • U have right. It should be $('#div1')[0].innerHTML = moreDom. But then it will not look to great. – Kamil Kaźmierowski Nov 11 '15 at 22:27
  • How it looks doesn't matter if it doesn't work :P Of course you could simply use the jQuery API: `$('#div1').html('0')` which works *and* looks better. – Felix Kling Nov 11 '15 at 22:30
  • And how about that? https://jsfiddle.net/2dqaqyjo/ :) But with API you mentioned, it will look better :D – Kamil Kaźmierowski Nov 11 '15 at 22:38
  • Maybe you misunderstood me. You seem to have implied that the current solution doesn't look as "nice" as the previous one. All I was saying is that it doesn't matter how "nice" it looks if it doesn't work. Meaning while the previous version may have looked "nicer", it didn't work. – Felix Kling Nov 11 '15 at 22:40