dk.win
dk.win

Reputation: 53

Uncheck checkbox and hide parent when button is clicked

The following code I wrote is supposed to have a row of check boxes, and when selected, displays the label of that check box in a separate div.

     <div class="span3" id="bill">
          <label class="checkbox">
            <input type="checkbox" value="" id="item1" checked="checked">
            Item1 - Price
          </label>
          <label class="checkbox">
            <input type="checkbox" value="" id="item2" checked="checked">
            Item2 - Price
          </label>
        </div>
        <div class="span3" id="currBill">
          <label id="item1_lb">
            Item1 - Price
          </label>
          <label id="item2_lb">
            Item2 - Price
          </label>
        </div>
      </div>
      <div class="row-fluid">
        <button class="btn" id="pay">Pay</button>
      </div>

the following js takes care of displaying the labels when selected/unselected (It's sloppy for know, all the check boxes will later be filled in from a database, this is just some place holding code for the general idea of my problem.)

Neither of the two functions seem to be working, the on click function at least triggers, but doesn't actually hide anything. Any ideas?

$(function() {
  $('input:checkbox').bind('change',(function() {
    $('#'+ithis.id+'_lb').toggle($(this).is(':checked'));
  });

  $("#pay").click(function() {
    $("#bill input[type=checkbox]").each(function() {
      if($(this).checked)
      {
        $(this).parent().hide();
        $(this).checked = false;
      }
    });
  });
});

Upvotes: 3

Views: 561

Answers (2)

Tomas Ramirez Sarduy
Tomas Ramirez Sarduy

Reputation: 17471

You should use the Browser Console to check the errors (press Ctrl+Shift+J). You have the following errors:

  • In line 2 ('change',(function(), drop the parenthesis before function keyword.
  • ithis.id should be this.id.
  • Instead check if($(this).checked) should be like you did first: if($(this).is(':checked'))
  • To deselect the checkbox use $(this).prop('checked', false);

Fiddle here: http://jsfiddle.net/qKPGd/

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191749

$(this).checked tries to access a jQuery collection attribute checked. You can alter element properties via the .prop method.

if ($(this).prop('checked')) {
    ...
    $(this).prop('checked', false);

Upvotes: 2

Related Questions