Lawrence
Lawrence

Reputation: 727

Jquery append when radio button selected

I don't know why but hopefully, someone can help me out with the following code.

    <script src="/jquery-1.7.2.min.js"></script>
    <script>
    $(".static_class").click(function(){
        if($(this).val()==="expanded") 
            $(".widget_prev").append("<p>expanded</p>"); 
        else $(".widget_prev").append("<p>minified</p>");
    });
    </script>

    <div>
    <input type="radio" name="ad_window" selected="selected" value="expanded" class="static_class" />Ad Window Expanded
    <br />
    <input type="radio" name="ad_window" value="minified" class="static_class" />Ad Window Minimized
    <b>Widget Preview: </b>
    <div class="widget_prev"></div>
    </div>

Can't seem to get the text appended. Wonder where the problem lies.

Upvotes: 1

Views: 866

Answers (4)

user1432124
user1432124

Reputation:

Put code inside $(function(){//here}); Try this smarter way

    <script>
$(function(){    $(".static_class").click(function(){
                 $(".widget_prev").append("<p>"+this.value+"</p>"); 
                 });
});
        </script>

Upvotes: 0

Sang Suantak
Sang Suantak

Reputation: 5265

Wrap your jquery code within $(document).ready({});

Upvotes: 1

Sampson
Sampson

Reputation: 268344

Make sure you wait for the elements to be in the DOM before you bind your click event. In the following, I'm using the short-form of $(document).ready(), which is $(function(){ /* ... */ });

$(function(){

  $(".static_class").on("click", function(e){
      $("<p>").text(function(){
          return $(e.target).val() === "expanded" ? "expanded" : "minified" ;
      }).appendTo(".widget_prev");
  });

});

Fiddle: http://jsfiddle.net/jonathansampson/drkCK/

Upvotes: 1

Steve
Steve

Reputation: 3046

Place the script below the radio buttons/div.

Upvotes: 0

Related Questions