开发者

jQuery change checkbox button text when clicked

I have some jQuery checkbox buttons, and they work fine. However, I would like to change their text开发者_如何学JAVA upon a click. for example: the button's text is "click me". when the user clicks it, i needs to change to "thanks for clicking", for example.

This is what I am trying using:

<script>
    $(function() {
        $("#button").button(); 
        $("#button").click(function(){
            if($("#label").is(':checked')) {
                $("#label span").text("Hide");
            }
            else {
                $("#label span").text("Show");
            }
        });
    }); 
</script>
<input id='button' type='checkbox' />
<label id='label' for="button">Show/Hide</label>


This is your first problem:

       if($("#label").is(':checked')) {

<label> elements don't get "checked" only their checkboxes do. Change it to:

if (this.checked) {

In the code above, this refers to the checkbox element that has been clicked, and we're looking to see if the checked property contains the value true. It's much more efficient that .is(':checked').

Also, the <label> element has no <span> child, it just has text, so

            $("#label span").text("Hide");

should be

            $("#label").text("Hide");

But you could shorten the whole thing using the ternary conditional operator:

    $("#button").click(function(){
        $("#label").text(this.checked ? "Hide" : "Show");
    }

Working demo: http://jsfiddle.net/AndyE/qnrVp/


$("#button").click(function() {
    if($(this).is(':checked')) {
        $("#label").text("Hide");
    } else {
        $("#label").text("Show");
    }
});

And here's a live demo.


Try this:

$("#button").click(function(){
     var th = $(this);
     if(th.is(':checked')) {
          $("label[for=" + th.attr('id') + "]").text("Hide");
     } else {
          $("label[for=" + th.attr('id') + "]").text("Show");
     }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜