Rumen Panchev
Rumen Panchev

Reputation: 498

Checkbox is not disabled after checking other checkbox

I have 2 checkboxes:

<div>
    <input type="checkbox" id="dx_article_excerpt">
    <label for="dx_article_excerpt">
        <?php _e( 'Displayyyyyyyy Excerpt', 'dxeasypb' ); ?>
    </label>
</div>
<div>
    <input type="checkbox" id="dx_article_content">
    <label for="dx_article_content">
        <?php _e( 'Display Content', 'dxeasypb' ); ?>
    </label>
</div>

I want when the first is clicked, the content checkbox to be disabled automatically. I've tried the following thing:

if (document.getElementById('dx_article_excerpt').checked) {
    document.getElementById("dx_article_content").disabled = true;
}

But guess what.. it's not working.

Upvotes: 0

Views: 50

Answers (3)

prasanth
prasanth

Reputation: 22500

Why is not working?

  1. Because no event is there .assign onchange event

    onchange="change()"

  2. Wrap the js inside the function

Updated with toggle

function change(){
        document.getElementById("dx_article_content").disabled = document.getElementById('dx_article_excerpt').checked;
}
<div><input type="checkbox" id="dx_article_excerpt" onchange="change()"><label for="dx_article_excerpt"><?php _e( 'Displayyyyyyyy Excerpt', 'dxeasypb' ); ?></label></div>
<div><input type="checkbox" id="dx_article_content"><label for="dx_article_content"><?php _e( 'Display Content', 'dxeasypb' ); ?>

Upvotes: 1

guradio
guradio

Reputation: 15555

$(".checkbox").change(function() {
  $(".checkbox").not(this).prop("disabled", $(this).is(":checked"))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><input type="checkbox" id="dx_article_excerpt" class="checkbox"><label for="dx_article_excerpt">1</label></div>
<div><input type="checkbox" id="dx_article_content" class="checkbox"><label for="dx_article_content">2</label></div>
1. Add a class for both checkbox. 2. Use the status of current checkbox changed to prop disabled of the other checkbox

Upvotes: 1

Bourbia Brahim
Bourbia Brahim

Reputation: 14712

Use click event to change the content check status as below snippet using jquery :

$(function() {
  $("#dx_article_excerpt").click(function(){
     $("#dx_article_content").prop("disabled",this.checked);
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><input type="checkbox" id="dx_article_excerpt"><label for="dx_article_excerpt">first</label></div>
<div><input type="checkbox" id="dx_article_content"><label for="dx_article_content">content</label></div>

Upvotes: 1

Related Questions