-2

I am trying to create a if statement that triggers a alert box if there is text in the div.

My Jsfiddle: http://jsfiddle.net/D7cPT/21/

My HTML:

<div id="post-preview">aasasdasd</div>

MY JQUERY:

$(document).ready(function() {
    // Bind it to some action.
    if{$('#post_body_html').html();) {
       alert('asdasda');
      }
});
Manse
  • 37,765
  • 10
  • 83
  • 108
Rails beginner
  • 14,321
  • 35
  • 137
  • 257

4 Answers4

13

OH DEAR GOD:

//why is there a bracket after the if and a semicolon in there?
if{$('#post_body_html').html();) { 

How about:

//change if{ to if( and remove semicolon
if($('#post_body_html').html()) {

Also your selector doesn't match the ID of your element. Change #post_body_html to #post-preview

jsFiddle

Edit:

To those who land here later on, a better way to accomplish the same test is written:

if($('#post_body_html')[0].childNodes.length) {

instead.

Chad
  • 19,219
  • 4
  • 50
  • 73
  • 1
    I love the 'lightbulb' moment where we try to pretend that that was the biggest thing wrong with that code - :P we all gotta start somewhere. – rlemon Nov 28 '11 at 22:01
  • 1
    Note that `.html()` is foolish, you probably want something like `[0].childNodes.length` instead – Raynos Nov 28 '11 at 22:43
  • @Raynos added to answer, just in case. – Chad Nov 29 '11 at 01:10
3

Try this ->

$(document).ready(function() {
    // Bind it to some action.
    if($('#post-preview').html()) { // wrong ID and wrong syntax
       alert('asdasda');
     }
});

Working demo : http://jsfiddle.net/manseuk/D7cPT/25/

Manse
  • 37,765
  • 10
  • 83
  • 108
0

You have MANY problems:

  1. It should be post-preview, not #post_body_html
  2. You have if { instead of if (
  3. You end your if statement with a semi-colon? Huh?
  4. html() doesn't return a bool, it returns a string.

Try this:

$(document).ready(function() {
    // Bind it to some action.
    if ($('#post-preview').html().length > 0) {
       alert('asdasda');
      }
});
aquinas
  • 23,318
  • 5
  • 58
  • 81
  • An empty string would evaluate the `if` statement to false. `.length > 0` is not *really* necessary. See [this answer](http://stackoverflow.com/questions/154059/what-is-the-best-way-to-check-for-an-empty-string-in-javascript) – Chad Nov 28 '11 at 21:47
  • True, it's only necessary for my sanity ;) – aquinas Nov 28 '11 at 21:53
-3

You should remove the ;

$(document).ready(function() {
    // Bind it to some action.
    if{$('#post_body_html').html()) { //line changed
       alert('asdasda');
      }
});
Adilson de Almeida Jr
  • 2,761
  • 21
  • 37