HTML
For the HTML part, there are two ways to specify a label for an element:
-
Setting the label's for
attribute to the element's id
<input type='checkbox' id='chkCart' />
<label for='chkCart'>Add to Cart</label>
-
Placing the element inside a label
<label >
<input type='checkbox' />
Add to Cart
</label>
I'll use the first one
JavaScript
Then you can use jQuery to handle the rest:
- First, make sure the DOM is loaded by wrapping your javascript in a
.ready
function (since we'll be looking to modify these elements).
- Then attach an event handler to the checkbox click event by using the
.click
function.
- Since we've set the
for
attribute for this particular label, we can use the attribute
equals selector ([name="value"]
) by looking for a label with the same for
value as our calling element's id
.
- You can check if the object that raised the event is checked on or off by using the
:checked
selector.
- You can use the Javascript's
ternary
operator to conditionally set each value
- Then rename the label using the
.text
function
It should all look like this:
$(function () {
$("#chkCart").click(function () {
var lbl = $(`label[for='${this.id}']`);
var msg = this.checked ? "Added" : "Add to Cart"
lbl.text(msg);
});
});
Demo in Stack Snippets & jsFiddle
<!-- begin snippet: js hide: true console: false babel: false -->
<!-- language: lang-js -->
$(function () {
$("#chkCart").click(function () {
var lbl = $(`label[for='${this.id}']`);
var msg = this.checked ? "Added" : "Add to Cart"
lbl.text(msg);
});
});
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input type='checkbox' id='chkCart'/>
<label for='chkCart'>Add to Cart</label>
<!-- end snippet -->