6

I just want to use a simple checkbox, for example, a checkbox with 'Please check this' next to it, then when it's clicked the text changes to 'Checked'

I've been looking all over for a simple solution, but struggling and can't figure it out - despite the simplicity.

Can somebody help me?

madth3
  • 7,275
  • 12
  • 50
  • 74
50dollanote
  • 189
  • 4
  • 4
  • 12

2 Answers2

12

Using jQuery:

$('#boxid').click(function() {
  if ($(this).is(':checked')) {
    $(this).siblings('label').html('checked');
  } else {
    $(this).siblings('label').html(' not checked');
  }
});

and in your HTML:

<input id="boxid" type="checkbox"><label for="boxid">not checked</label>

EDIT:

Working fiddle: http://jsfiddle.net/zpzxM/

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Positivity
  • 5,406
  • 6
  • 41
  • 61
  • 1
    Thank you! Tired eyes couldn't figure this out! So simple! – 50dollanote Aug 24 '13 at 20:56
  • @50dollanote you'r welcome **Important** I just used .click so this doesn't work if the user check the box using keyboard, you can use .change etc. – Positivity Aug 24 '13 at 22:52
  • @50dollanote well checked the fiddle and it also works when I use keyboard! strange! – Positivity Aug 24 '13 at 22:56
  • I think this is the answer he's looking for: http://stackoverflow.com/questions/6293588/how-to-create-an-html-checkbox-with-a-clickable-label – Adrian P. Feb 17 '14 at 19:35
1

JavaScript:

function changeText(id){

  if ($('#'+id).is(':checked')) {
    $('#'+id +"+span").html('Checked');
  }else{
    $('#'+id+ "+span").html('Please check this.');
  }
}

CSS:

<input type="checkbox" id="123" onclick="changeText(this.id);"><span>Please check this.</span>

"live Example"

  • You can also use ~ instead of + in the selector. That will also give you the same result. But for your case use of + is favorable as you only want to edit the adjacent sibling only. – Sanjeev Chauhan Aug 24 '13 at 21:20