Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
143
rated 0 times [  144] [ 1]  / answers: 1 / hits: 17662  / 14 Years ago, mon, january 31, 2011, 12:00:00

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>

More From » jquery

 Answers
15

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/


[#93968] Saturday, January 29, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kerryoliviaa

Total Points: 221
Total Questions: 102
Total Answers: 117

Location: Sint Maarten
Member since Tue, Mar 29, 2022
2 Years ago
;