admin管理员组

文章数量:1303641

I have some jQuery checkbox buttons, and they work fine. However, I would like to change their text 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>

I have some jQuery checkbox buttons, and they work fine. However, I would like to change their text 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>
Share Improve this question asked Jan 31, 2011 at 16:25 Tanner OttingerTanner Ottinger 3,0604 gold badges25 silver badges29 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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/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");
     }
});

本文标签: javascriptjQuery change checkbox button text when clickedStack Overflow