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');
});
});
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.
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.
Just give them all the same class, say, myClass. Then:
$('a.myClass').click(function () {
$(this).css('background':'red');
});
This will work as long as you're having the links operate on themselves, or on their parents - as long as the relationship between link and target is the same for each. To operate on the parent, it would be $(this).parent().css(...), and to operate on the next element it would be $(this).next().css(...) and so on.
have you tried something like this?
while($row = mysql_fetch_array($results)){
$title = $row['title'];
$i++;
echo '<a class="anchor_link" id="'.$i.'">'.$title.'</a>';
}
And then for the jQuery:
$(document).ready(function() {
$('a.anchor_link').click(function() {
var thisAnchor = $(this).attr('id');
$(this).css('background':'red');
});
});
The reason for my adding the js var 'thisAnchor' is because I am assuming that you need that $i php variable as the anchor marker? if so you can just take the js var and use it however you need. if you can't use ID because the anchored content is marked by id, use a diferent attr, such as 'title' or 'alt'.
I hope this was helpful.
Related
I have the following PHP that returns records from a my MYSQL table. These records are displayed as LINKS. See code below...
<div class="slide1" id="u1026">
<?php while ($row = mysql_fetch_array($query_rental)) {
echo "<a class='fancybox fancybox.iframe' id='rental' value={$row['layout']} href=\"brochures\items-rental.php?id={$row['client_name']}\"></a>";
}?>
</div>
What I would like, is for the HREF link to change to
\"brochures\items-rental-layout2.php?id={$row['client_name']}\
If VALUE contains the text "layout2". I know that I can change HREF using jquery code
$(document).ready(function () {
$("#event").attr("href", "http://the.new.url")
});
I'm just not sure how to do that depending if the VALUE contains text "layout2". Any help is much appreciated. Thanks
You can just do it straight in the PHP code:
while ($row = mysql_fetch_array($query_rental)) {
$layoutFlag = $row['layout'] == 'layout2' ? '-layout2' : '';
echo "<a class='fancybox fancybox.iframe' id='rental' value=\"{$row['layout']}\" href=\"brochures\items-rental{$layoutFlag}.php?id={$row['client_name']}\"></a>";
}
You could also do it with Javascript:
$(function () {
// I'm assuming you are going to turn it into a rental class, otherwise change the selector to whatever.
$("a.rental").each(function() {
var rentalItem = $(this);
if (rentalItem.attr('value') === 'layout2') {
// You can choose what to replace, as long as you know it will replace EXACTLY what you want it to. I'm just going with Regex's ^ (start-of-line) operator to make sure that what we are replacing is at the start of the line...
rentalItem.attr('href', rentalItem.attr('href').replace(/^brochures\\items\-rental/, 'brochures\\items-rental-layout2'));
});
});
As you can see, just doing it in PHP is so much easier.
Also as a side note, you are creating multiple elements with the same id. Maybe you meant class='fancybox fancybox.iframe rental'?
And as a second side note, I suggest using the data- prefix for holding custom data. In layout's case, use data-layout='layout-whatever'. You can then use .attr('data-layout') to get the layout attribute (it's easier to understand what that code is doing too!).
You can either run the IF statement on the PHP loop
while ($row = mysql_fetch_array($query_rental)) {
echo "<a class='fancybox fancybox.iframe' id='rental' value={$row['layout']} href=\"brochures\items-rental".($row['layout'] == 'layout2' ? '-layout2' : '').".php?id={$row['client_name']}\"></a>";
}
Or by jQuery
$( "a.fancybox" ).each(function( index ) {
if($(this).val() == "layout2") {
oldHref = $(this).attr('href');
newHref = oldHref.replace('items-rental.php', 'items-rental-layout2.php')
$(this).attr('href', newHref);
}
});
all your links have the same ID which can cause some issues when you wuold want to work with them with jQuery.
If you have more a tags with the fancybox class, try adding a unique class to these tags and update the each loop
I have two divs as shown below :
<div class="a b">Hello</div> // div with two classes
<div class="a"> Hii </div> // div with single class.
Both divs have a common class "a". I want to get value OR text of div with class "a" only i.e Second div. It should not fetch the value of first div.
P.S : There is no id for both the divs SO Don't say to use different IDs. I want it using class only.
$('.a').not('.b').text()
Use the .not selector to filter out undesidered elements: http://api.jquery.com/not-selector/
Alternatively, to really make sure you only selects divs with class a
$('div[class="a"]')
For further reference: jQuery: Is it possible to select elements with only one class from among elements with, potentially, up to 3 classes?
Here is the code you should use to check weather it has only class a or any other class too..
$('.a').each(function(){
var classList = $(this).attr("class");
classList = classList.trim().split(" ");
if(classList.length ==1){
//do your stuff
}
});
or you can use
$('.a').each(function(){
var classList = $(this).attr("class");
classList = classList.trim();
if(classList === "a"){
//do your stuff
}
});
Yeah but what if you don't know which other class may be included or what type of element we use?
(assuming we use jQuery)
$('.a').each(function(i, ele){
if($(ele).attr('class')==='a'){
// get value or text here
}
});
This is faster though
$('[class="a"]').each(/* get our values with a function in here */)
Its simple we can take only if we want to select only one class we can use like following
$('div[class="a"]') this will fetch the div have only class a
<div class="a b">Hello</div> // div with two classes
<div class="a"> Hii </div> // div with single class.
script
console.log($('div[class="a"]').html());
FIDDLE DEMO
You can achieve that styling with Just Pure CSS(CSS3),
div:not(.b){color:red;}
http://jsfiddle.net/WndAf/
jQuery Solution, to get the Div text
$(function() {
console.log($("div:not(.b)").text());
});
http://jsfiddle.net/WndAf/5/
I am generating divs in PHP, from an array, thus:
echo "<div id='parentdiv'>";
for($counter = 0; $counter < count($list); $counter++){
echo "<div>".$list['important_info']."</div>";
}
echo "</div>";//parentdiv
I want to add some click functionality to each div independently, i.e. the action performed on clicking depends on the div, and more importantly the index of the array, $list;
I want to give each div an id based on it's index in the PHP array.
So I could do
echo "<div id='"."divindex_".$counter."'>".$list['important_info']."</div>";
where "divindex_" is just used to prevent the id form beginning with a numeric value.
Then, I think in jQuery I can write click functions for each div.
However the problem is the $list size is variable, so I don't know how many divs there are.
So what I'm thinking is something like,
$("#parentdiv div").click(function(){
var id = split($(this).attr('id').split("_")[1];//get the php index from the id
//do something with the id, e.g. ajax or whatever
});
Is there a better way to do this? If you think what I'm doing is strange and not a very good idea, then I understand. But I don't know how to do this any other way. Any help appreciated.
Simply use:
$("#parentdiv div").click(function(){
var id = $(this).index(); //index of div, 0 based
var val = $(this).text(); //content of div, if you need it
});
No need to add unique IDs :) .
Demo:
http://jsfiddle.net/q9TaJ/
Docs:
http://api.jquery.com/index/
First, make sure to properly escape your outputs:
echo '<div id="parentdiv">';
for ($counter = 0; $counter < count($list); $counter++){
echo sprintf('<div data-id="%d">%s</div>',
$counter,
htmlspecialchars($list['important_info'])
);
}
echo '</div>';//parentdiv
I'm also using a special attribute called data-id which you can easily access in jQuery with this code:
$('#parentdiv > div').on('click', function() {
var id = $(this).data('id');
});
you can pass your variables as html attributes. Then bind the click event to a single class.
<div class="divs" data-id="myid"></div>
in jquery
$('.divs').click(function(){
console.log($(this).data('id));
});
I have been a really big fan of stackoverflow(which led me to ask the question here and not anywhere else), anyway, without further ado...
While creating a shop system, I planned to implement an ajax which buys the item on the fly. Now This is how the loop for retrieving items looks like:
<?php
$shop_query = mysql_query("SELECT * FROM sector0_item WHERE 1");
$numrows = mysql_num_rows($shop_query);
While ($shop_fetch = mysql_fetch_array($shop_query)){
?>
<div id="shop_main">
<div class = 'item_img'>
<a><img src = "http://images.wikia.com/dofus/images/4/4e/Discovery_Potion.png" height = '100px'/></a>
</div>
<div class="item_buy">
<a><center>Price: <?php echo number_format($shop_fetch['item_price']);?></center><br /></a>
<a>Quantity: <input type = 'text' size = '9' id = 'itemquantity'/><br /></a>
<a><p>Point requirement: <?php echo number_format($shop_fetch['item_pt_req']);?></p></a>
<a><input type = 'button' id = 'buy' value = 'buy'/></a><span id = 'buy_status'></span>
</div>
<a><h3><?php echo $shop_fetch['item_name'];?></h3></a>
<a><p><?php echo $shop_fetch['item_desc'];?></p></a>
<a>Item Type: <font color = 'green'><?php echo $shop_fetch['item_class'];?></font></a>
</div>
<br />
<?php
}
?>
However, my ajax seems to act really weird. My implementation was to show a loading gif image.
Script:
<script type = 'text/javascript'>
$('#buy').click (function(){
var quantity = $('#itemquantity').val();
$('#buy_status').html('<img src = "http://www.antibodyresource.com/theme/js/ajax-loader.gif" height = 20px;/>');
});
</script>
The problem is, Only one button shows the circle when clicked. Does the position of the script cause this? Any help is appreciated.
You can only have one item with a given id. When you have multiple elements with the same id, it is indeterminate which one will be returned, but it will usually be the first item only.
If you want multiple buy buttons and want to assign them all the same jQuery event handler, then use a common class name instead of an id.
If you are loading content dynamically and you want event handlers to work for that content, then you need to use delegated event handling.
In jQuery, that is generally done with either .on() or .delegate(). The basic idea is that you pick a static parent object that is not dynamically loaded (perhaps the parent of show_main) and bind the event to that object and then pass the selector of the dynamic element like this (note, I've changed from an id to a class to identify the buy button):
$(staticParentSelector).on('click', '.buyButton', function() {
$(this).closest(".item_buy").find(".buy_status").html('<img src = "http://www.antibodyresource.com/theme/js/ajax-loader.gif" height = 20px;/>');
})
Two things:
It's hard to tell from the sample, but is there an iterator that creates a list of available items? If so, you shouldn't be using IDs which are meant to be unique. If there's really only one #buy then you're fine, though.
When content is updated with Ajax, you're going to lose bindings. Assuming the item related to the #buy button gets replaced with other items, you're better off with a delegated event:
// not in an inline script, but just once, ideally in your main JS file
$(document).ready(function() {
$('#wrapper').on('click', '#buy', (function(){
var quantity = $('#itemquantity').val();
$('#buy_status').html('<img src = "http://www.antibodyresource.com/theme/js/ajax-loader.gif" height = 20px;/>');
});
})
Where #wrapper is some ancestor higher up in the DOM tree that is never destroyed by the Ajax event.
id is unique value - on html page each id must have unique value. Use class instead.
You need to put your code inside $(document).ready(). So its:
$(document).ready( function() {
$('#buy').click( function(){
// do something here
});
});
Also, you may want to list to jfriend00's advice on IDs.
I have the code bellow inside a wordpress loop, so the variable $perf and $url change every time.
<div class="link" data-performer="<? echo $perf; ?>">
<a class="performer_rp" href="<? echo $url; ?>">My anchor</a>
</div>
This jquery function ads the variable $perf to the link, on click.
function performer_rp(){
var perf;
perf = $(".link").data('performer');
$("a.performer_rp").click(function() {
this.href += "?perf="+perf+"";
});
};
Problem is, I get only the first value of $perf, it won't change with the loop.
So lets say the loop "loops" 5 times and I get 5 $perf values: value1, value2 ... value5.
The jquery code asigns the value1 everytime.
Why is that?
Ty very much!
Well 'id do it this way:
function performer_rp(){
var perf;
$("a.performer_rp").click(function() {
//get the value from the parent (as suggessted in the comment you can also use
//$(this).closest('div.link').data('performer'); if the '<a>' is not a direct child of the div
perf = $(this).parent().data('performer');
this.href += "?perf="+perf+"";
});
};
otherwise you have the same perf each time (because it's not relative to the link you click), and you are getting a collection of perfs anyway.
Edit: i don't know exactly how data() works, but i think you could use:
perf = $(this).parent().attr('data-performer');
The selector
$(".link");
Is getting a collection that contains all of your links (say 5 in your example).
When you do this
perf = $(".link").data('performer');
You are getting the data value of the first element in the collection only
Hello I not sure if I've got your question. Why to assign values in the moment of a click?
Instead you can try this in order to assign all 'data-performer' values just after the page is loaded.
$(document).ready(function() {
$(".link").each(function(){
var parent = $(this),
old_link = parent.find('a.performer_rp').attr('href');
new_link = old_link + "?perf="+parent.data('performer');
parent.find('a.performer_rp').attr('href', new_link)
});
});
example at:
http://jsfiddle.net/USEkF/