Sonam Mohite
Sonam Mohite

Reputation: 903

How to uncheck a checkbox on unselection of a particular checkbox

I want to uncheck checkbox based on unselection of another check box. ex.

    <input id=isActive_1 type=checkbox />
<input id=isActive_2 type=checkbox />
<input id=isActive_3 type=checkbox />


    <input id=publish_1 type=checkbox />
<input id=publish_2 type=checkbox />
<input id=publish_3 type=checkbox />

when i uncheck 'isActive_1' then 'publish_1' should be unchecked at this time. Please help me out

Upvotes: 0

Views: 320

Answers (5)

AnthonyLeGovic
AnthonyLeGovic

Reputation: 2335

$("input#isActive_1").click(function(){
 if($('input#isActive_1:checked').length > 0)
   $('input#publish_1').attr('checked', true);
 else
   $('input#publish_1').attr('checked', false);
});

Edit : Wrong test to know if "isActive_1" checkbox is checked or not on first time.

Upvotes: 0

Xeon
Xeon

Reputation: 5989

You should try this: JSFiddle

$(function() {
    $(document).on("click", "input[id^='isActive_']", function() {
        var number = +$(this).attr("id").substring(9);
        var checked = $(this).prop("checked");

        // for checking & unchecking behaviour
        //$("#publish_"+number).prop("checked", checked);

        if(!checked) {
            $("#publish_"+number).prop("checked", false);
        }
    });
});

(or with "change" event)

You can now add as many checkboxes as you like and even dynamically (e.g. after page is loaded & JavaScript executed - from AJAX)

Upvotes: 0

Adil
Adil

Reputation: 148120

First of all use double quotes for attribute values, and use the id of isActive_ checkboxes to get the index of publish_

Live Demo

Html

<input id="isActive_1" type="checkbox" />
<input id="isActive_2" type="checkbox" />
<input id="isActive_3" type="checkbox" />
<input id="publish_1" type="checkbox" />
<input id="publish_2" type="checkbox" />
<input id="publish_3" type="checkbox" />

Javascript

$('[id^=isActive_]').change(function () {
    $('#publish_' + this.id.replace('isActive_', '')).attr('checked', this.checked);
});

Upvotes: 0

Anujith
Anujith

Reputation: 9370

See this: Fiddle

$('input[id^=isActive_]').change(function () {
   $("input[id^=publish" + this.id.replace('isActive', '') + "]").attr('checked', this.checked);
});

Upvotes: 2

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

You can use this:

$(document).ready(function(){
    $("input#isActive_1").click(function(){
        if(!$("input#isActive_1").prop("checked"))
          $("input#publish_1").prop("checked", false);
        else
          $("input#publish_1").prop("checked", true);
    });
});

Fiddle: http://jsfiddle.net/praveenscience/uJxL8/


Updated from comment

Use regex selectors this way:

$(document).ready(function(){
    $("[id^=isActive_]").click(function(){
        /////
    });
});

Upvotes: 0

Related Questions