Qcom
Qcom

Reputation: 19173

No alert popping up, although variable is defined, and syntax LOOKS correct

Here's my code:

$(document).ready(function(){

  var Bold="Yes!  There is bold in the text above!!";
  var NoBold="No... There isn't any bolded text in the paragraph above..";
  var BoldButton='<input class="BoldButton" type="button" value="Bold?" id="WelcomeBoldButton">';

  $(BoldButton).insertAfter('#intro');
  $(BoldButton).insertAfter('#LatestNews');

  $(BoldButton).click(function(){
    if($(this).prev().is(':has(b, strong)')){
      alert(Bold);
      } else {
        alert(NoBold);
      }
});

});

For some reason, the alert won't pop up upon clicking the instances of the variables even though the buttons are showing up..

UPDATE:

Here is a working version of the code. I apologize but I'm still very new to JS and jQuery but I don't really understand why this version is working..

$(document).ready(function(){

  var Bold="Yes, some of this text is Bolded!";
  var NoBold="No, none of this text is Bolded..";
  var BoldButton='<input class="BoldButton" type="button" value="Bold?">';
  var MakeMeMoreBoldButton='<input class="MakeMeMoreBoldButton" type="button" value="MakeMe More Bold!">';
  var MakeMeBoldButton='<input class="MakeMeBoldButton" type="button" value="Make Me       Bold!">';

  $(BoldButton).insertAfter('#disclaimer');
  $(BoldButton).appendTo('#navigation');
  $(BoldButton).insertAfter('#intro');

  $('.BoldButton').click(function(){
  if($(this).prev().is(':has(b, strong)')){
  alert(Bold);
  $(this).prev().addClass('BoldText');
  $(MakeMeMoreBoldButton).insertAfter(this).prev();
  $('.MakeMeMoreBoldButton').click(function(){
    $('.BoldText').css('font-weight', 'bold');
  });
  }  
else{
  alert(NoBold);
  $(this).prev().addClass('MakeMeBold');
  $(MakeMeBoldButton).insertAfter(this).prev();
  $('.MakeMeBoldButton').click(function(){
    $('.MakeMeBold').css('font-weight', 'bold');
  });
  }
  });
  });

Upvotes: 3

Views: 137

Answers (3)

Stefan Kendall
Stefan Kendall

Reputation: 67832

Move the event handler before the insertions. A better way to do this, however, is this:

  $('.BoldButton').live('click',function{

     if($(this).prev().is(':has(b, strong)')){
       alert(Bold);
     } else {
       alert(NoBold);
     }
 });

Upvotes: 1

Pointy
Pointy

Reputation: 413757

That's not going to work, as you've demonstrated by empirical testing. What you're doing is creating some DOM content and then copying it a couple times into the document. You need to set up your "click" handlers on the real DOM nodes that are actually in the document.

Upvotes: 4

Coding Flow
Coding Flow

Reputation: 21881

Have you tried attatching the click event before inserting the buttons into the DOM.

Upvotes: 0

Related Questions