Jeff Walters
Jeff Walters

Reputation: 161

jQuery Checkbox toggle function not working

I'm trying to make a function that changes the color of text when a checkbox is checked. It was working fine, but all of the sudden now it won't work It says that the toggle variable is an undefined expression, but it's just an id tag being stored in it. also, the css changes weren't working, even when the alert would pop up. I would greatly appreciate any info on why this function suddenly broke.

JavaScript, jQuery code:

function estimateToggle(toggle)
{ 
    var toggle = "#" + toggle;
    alert(toggle);

    if  ($(toggle).is(":checked"))
    {
        alert(toggle + " is checked");
        $("'" + toggle + "'").css({'color':'black'});
    }else{
        alert(toggle + " is unchecked");
        $("'" + toggle + "'").css({'color':'#CCCCCC'});
    }

}

HTML code:

<input type="checkbox" class="socialMedia" name="socMedFacebook" id="socMedFacebook" onChange="estimateToggle('socMedFacebook')" value="100">
<label for="socMedFacebook">Facebook</label>
<div align="right" class="socMedFacebook" id="socMedFacebook" name="socMedFacebook">$100</div>

Here is the error that Chrome Console spits out:

Uncaught Error: Syntax error, unrecognized expression: '#socMedFacebook'

Upvotes: 1

Views: 204

Answers (1)

ID selector must be unique .

Read Two HTML elements with same id attribute: How bad is it really?

change to

$(toggle).css({

form

 $("'" + toggle + "'") // as your variable toggle  is already string don't wrap quotes around it.

Upvotes: 2

Related Questions