Kissa Mia
Kissa Mia

Reputation: 297

How to select an element with dynamically generated class and id at the same time?

HTML

120:    $seperator= "<SEPERATOR>";
121:    echo "<div class='optionBox' onClick='selectOther(this.id)' id='".$OPid.$seperator.$OPlayer2ID."' >".$OPlayer2nam."</div>";

Jquery

function selectOther(evalOTHERID){
   $("div[.*'selected'#'"+evalOTHERID+"']").css('opacity', '1');
   $("div[id='"+evalOTHERID+"']").css('opacity', '0.08');
   $("div[id='"+evalOTHERID+"']").addClass( "selected" );   
}

the HTML line #120 and #121 are in a while loop to generate selectable boxes, something like the one bellow

=====   =====   =====
=43 =   =44 =   =45 = 
=====   =====   =====

the opacity will be changed to 0.08 on click on each selectable boxes, My problem is how to deselect the previously selected one ? I tried to use the suggested solutions on jQuery: select an element's class and id at the same time? but it seems that there is something wrong with my integration.

I also tried to change it to:

    $("div[class*='selected'][id='"+evalOTHERID+"']").css('opacity', '1');

But it still won't change the opacity of the selected one back to 1.

I have googled the question tried to find an answer for it, it's true that there are bunch of solutions but I am new in web programming, and not able to integrate the correctly. there is no error in console by the way.

Please tell me in what way I can get the ID of the element that has class selected? I will be appreciated.

Please help me to edit the question if it isn't really clear, I'll learn more things then. Appreciated.

Upvotes: 0

Views: 914

Answers (1)

Wilmer
Wilmer

Reputation: 2511

You can simplify things a little bit by passing the dom node like:

onClick='selectOther(this)'

Then we wrap it in jQuery $(elem) and solve the problem:

function selectOther(elem){
   $(elem).toggleClass("selected");

    if( $(elem).hasClass("selected") ){
        $(elem).css('opacity', '0.08');
    } else {
        $(elem).css('opacity', '1');
    } 

}

Upvotes: 1

Related Questions