Dan
Dan

Reputation: 1719

Change CSS based on certain DIV content

Hoping someone could help me with a bit of jquery or javascript. I have some DIV's that contain the values of a checkbox being either "1" or "0" depending on whether I check the box or not:

<div class="checkbox">1</div>   //This is when the checkbox is checked

<div class="checkbox">0</div>   //This is when the checkbox is NOT checked

The class for this DIV stays the same whether it is a 0 or a 1 so I need to have a conditional statement that says,

"If the contents of the DIV is 1 then show it"

AND

"If the contents of the DIV is 0, then hide it"

Would this be simple to do?

Upvotes: 1

Views: 1011

Answers (5)

Jai
Jai

Reputation: 74738

If i have to do it then i would love to do in this way: http://jsfiddle.net/P2WmG/

var chktxt = $.trim($('.checkbox').text());
if (chktxt == 0) {
   $('#checkbox').hide();
} else {
   $('#checkbox').show();
}

Upvotes: 0

matthewtole
matthewtole

Reputation: 3247

You can use the :contains() Selector to select the divs based on their contents.

$('div.checkbox:contains("1")').show();
$('div.checkbox:contains("0")').hide();

Upvotes: -1

idrumgood
idrumgood

Reputation: 4924

Any time a checkbox is changed, look at your divs with class checkbox and if they have 1, show, else hide.

$('input[type="checkbox"]').on('change', function() {
    $('.checkbox').each(function(){
        if($(this).text() === '1'){
            $(this).show();
        }else{
            $(this).hide();
        }
    });
});

Upvotes: 0

Alexander
Alexander

Reputation: 23537

I would do it differently.

$("input#checkbox").change(function(){
  $("div.checkbox").toggle(this.checked);
});

Considering that your checkbox is the one that it is altering the content of the <div> anyways.

Upvotes: 2

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

A filter would come in handy for such case..

$('.checkbox').filter(function () {
   return $(this).text() == 0;
}).hide();

Upvotes: 3

Related Questions