Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Selectors with Jquery with php while loop

I have a while loop which creates a list of anchor tags each with a unique class name counting from 1 to however many items there are. I would like to change a css attriubute on a specific anchor tag and class when it is clicked so lets say the background color is changed. Here is my code

while($row = mysql_fetch_array($results)){
 $title = $row['title'];
 $i++;
 echo "<a class='$i'>$title</a>

}

I would like my jquery to look something like this, it is obviously going to be more complicated than this I am just confused as where to start.

$(document).ready(function() {
$('a .1 .2 .3 .4 and so on').click(function() {
$('a ./*whichever class was clicked*/').css('background':'red');
        });
   });
like image 994
Cool Guy Yo Avatar asked Dec 14 '25 09:12

Cool Guy Yo


2 Answers

Can you give the class a more consistent name? Like myClass_1, myClass_2, etc.

Then you could do:

$(document).ready(function() {
    $('a[class^=myClass_]').click(function() { // Assign handler to elements with a
                                               //  class that starts with 'myClass_'
        $(this).css('background','red');  // Change background of clicked one.

    });
});

Here, a "starts with" selector is used to assign the event to all classes that start with myClass.

You could still retrieve the index number if needed.

Within the event handler, $(this) refers to the one that was clicked.

Live Example: http://jsfiddle.net/Jurv3/

Docs for "starts with" selector: http://api.jquery.com/attribute-starts-with-selector/

EDIT: I had a missing ] in the selector. Fixed now.

like image 87
user113716 Avatar answered Dec 16 '25 23:12

user113716


You can use an iterator over an array like this:

var myclasses = [".1",".2",".3"]; // generated by php

$.each(myclasses, function(index, value) { 
    $('a '+value).click(function() {
        $(this).css('background':'red');
    });
});

Note: I think you might be better off using unique ID for each item in your list of anchor tags and have them all share a single class. That's more what classes and IDs are for.

like image 23
Keltex Avatar answered Dec 17 '25 01:12

Keltex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!