Daniel S
Daniel S

Reputation: 609

jquery control a checkbox from another checkbox

my check-boxes look like

<input type="checkbox" id="checkbox_1" name="artist" value="Yes">
<input type="checkbox" id="checkbox_2" name="song" value="Yes">

and my code is

$(document).ready( function() {
    $('#checkbox_1').click( function() {
        $('#checkbox_2').each( function() {
            this.checked = !this.checked;
        });
        $("#submit").click();
    });
});

problem is when i check checkbox_1 it doesnt stay checked (it stays deselected).. after $("#submit").click();

hope you get the ideea

ok ok ok ..

the desired effect is:

Step1: both checkboxes are cleared

Step2: if i select checkbox1 then both checkboxes are selected

Step2: if i deselect checkbox1 then both checkboxes are cleared again

get it ?

Upvotes: 2

Views: 923

Answers (2)

sdfadfaasd
sdfadfaasd

Reputation: 1446

$(function () {
  $('#checkbox_1').click(function () {
    $('#checkbox_2').prop('checked', $(this).prop('checked'));
  });
});

You don't need the .each unless there is more then one element.

http://jsfiddle.net/t3zgx/2/

Upvotes: 1

Struikel
Struikel

Reputation: 136

$(function () {
    var checkbox_one = $('#checkbox_1');
    var checkbox_two = $('#checkbox_2');

    checkbox_one.click(function () {
      if(checkbox_one.prop('checked'))
      {
          checkbox_two.prop('checked', 'checked');
      }
      else
      {
          checkbox_two.removeProp('checked');
      }
  });
});

Fiddle

Upvotes: 0

Related Questions