anubhav gupta
anubhav gupta

Reputation: 75

html jquery form checkbox

HTML:

<td>
    <input type="checkbox" name="lit" value="literary"><span class="checkdata">&nbsp;Literary Event&nbsp;&nbsp;</span>
    <input type="checkbox" name="art" value="art"><span class="checkdata">&nbsp;Art Event&nbsp;&nbsp;</span>
    <input type="checkbox" name="cul" value="cultural"><span class="checkdata">&nbsp;Cultural Event&nbsp;&nbsp;</span>
</td>

Script:

<script>
    $(function(){
        if ("input:checked") {
            $(".checkdata").css("color", "#F0F0F0");
        }
    });
</script>

What I'm trying to do here is to check, if the user has checked the checkbox. If so, the span class="checkdata" should turn grey. It does not happen though.

Upvotes: 1

Views: 1092

Answers (5)

Panos Bariamis
Panos Bariamis

Reputation: 4653

write your script as

$(function() {
    $('input[type="checkbox"]').click(function() {
        $(this).next('.checkdata').css('color', this.checked ? '#F0F0F0' : '#000000');
    });
});

Upvotes: 0

Philll_t
Philll_t

Reputation: 4437

 $("input[type='checkbox']").change(function (){
var perform = {
   true : {'color' : 'green'},
   false: {'color' : 'red'}
 }, chk = $(this);

 $(".checkdata").css(perform[chk.is(":checked")]);

});  

Prevent if statements :) Polymorphism.

Upvotes: 0

Jamir Khan
Jamir Khan

Reputation: 397

try this:

$(function(){

    if($("input").is(':checked')){
        $(".checkdata").css("color", "#F0F0F0");
    }

});

Upvotes: 0

Catalin
Catalin

Reputation: 11721

If you want to toggle the css when the checkbox value is changed, try this:

$(function () {
    $("input[type='checkbox']").change(function () {
        var isChecked = $(this).is(":checked");
        if (isChecked) {
            $(".checkdata").css("color", "#F0F0F0");

        } else {
            $(".checkdata").css("color", "#000000");
        }
    });
});

Upvotes: 0

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try This

$(function(){
    $('input[type="checkbox"]').each(function(){
        $(this).click(function(){
        if ($(this).prop('checked'))
        {
            $(this).next(".checkdata").css("color", "#F0F0F0");
        }
        else
            $(this).next(".checkdata").css("color", "#000000");

        });
    });
});

Test fiddle: http://jsfiddle.net/GQ4FY/1/

Upvotes: 1

Related Questions