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/
Related
I built a for each loop that pulls back several rows from the database. Each row it pulls has a link, and a hidden input box with a value of posting_id. This link will work similar to a like button on facebook in a way. The hidden input box just stores the posting_id. When you click the "like" link, it sends over the posting_id to a jQuery page and pings back a page called community to tell it the user has "liked" the post.
Here's the problem
I'm pulling several rows, and it seems that only the top row being pulled is actually sending the data to the jQuery page when you click the "like" button. If I click on any other "like" button other than the top one it will not work at all.
Jquery Page
$('.bump_link').click(function(){
var posting_id = $('.posting_id').val();
$.post("community.php", {
posting_id: posting_id
});
alert(posting_id);
$(this).toggleClass("bumped");
});
Foreach Loop
foreach ($result as $value) {
$group_postings .= '
<input type="text" class="posting_id" value="'.$value['posting_id'].'">
<div id="bump_icon" class="bump_link"></div>
<span id="counter"></span>
';
}
I hope I've made the issue clear, it was and is difficult to explain.
The problem is you are using a class to get the posting_id, since all the hidden fields have the same class only the first elements value is passed no matter what button you click.
i recommend using this html, without the hidden input, pass the value as a data attribute
<div id="bump_icon" class="bump_link" data-postid="'.$value['posting_id'].'">
and in this js, get the posting id from the data attribute
$('.bump_link').click(function(){
var posting_id = $(this).data('postid'); // get the posting id from data attribute
$.post("community.php", {
posting_id: posting_id
});
alert(posting_id);
$(this).toggleClass("bumped");
});
You are calling val() on selector you might return more then one elements, but val() will give you the value of one (first) element only. You can use map() to get all values of input having class posting_id
var posting_id_values = $('.posting_id').map(function(){
return this.value;
}).get().join(',');
Your problem is this line:
var posting_id = $('.posting_id').val();
This will return the first posting_id value every time, not the one associated with the bump_link you are clicking on.
There are lots of ways to solve this. One way is to use .prev() to select the previous element:
var posting_id = $(this).prev('.posting_id').val();
this selects the previous posting_id element from the current div. This relies on the fact that the posting_id element is before the associated bump_link div.
If you want to send just the posting_id of the clicked button, you could change your PHP/HTML code like this:
foreach ($result as $value) {
$group_postings .= '
<div id="bump_icon" class="bump_link">
<input type="text" class="posting_id" value="'.$value['posting_id'].'">
</div>
<span id="counter"></span>
';
}
And your JS code like this:
$('.bump_link').click(function(){
var posting_id = $(this).find('.posting_id').val();
$.post("community.php", {
posting_id: posting_id
});
alert(posting_id);
$(this).toggleClass("bumped");
});
use on delegated event since you are adding the content dynamically and
$(this).prev('.posting_id') // to get the posting data value
$(document).on('click','.bump_link',function(){
var posting_id = $(this).prev('.posting_id').val(); //<-- use $(this) reference
$.post("community.php", {
posting_id: posting_id
});
alert(posting_id);
$(this).toggleClass("bumped");
});
I have an index.php file that I would like to run getdata.php every 5 seconds.
getdata.php returns multiple variables that need to be displayed in various places in index.php.
I've been trying to use the jQuery .load() function with no luck.
It's refreshing the 12 <div> elements in various places on the index.php, but it's not re-running the getdata.php file that should get the newest data.
But If I hit the browser refresh button, the data is refreshed.
getdata.php returns about 15 variables.
Here is some sample code:
<script>
var refreshId = setInterval(function()
{
$('#Hidden_Data').load('GetData.php'); // Shouldn´t this return $variables
$('#Show_Data_001').fadeOut("slow").fadeIn("slow");
$('#Show_Data_002').fadeOut("slow").fadeIn("slow");
$('#Show_Data_003').fadeOut("slow").fadeIn("slow");
$('#...').fadeOut("slow").fadeIn("slow");
}, 5000); // Data refreshed every 5 seconds
*/
</script>
Here's an example of GetData.php:
$query = "SELECT column1, COUNT(column2) AS variable FROM table GROUP BY column";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$column1 = $row['column1 '];
$variable = $row['variable '];
if($column1 == "Text1") { $variable1 = $variable; }
elseif($column1 == "Text2") { $variable2 = $variable; }
... continues to variable 15 ...
}
Then further down the page the HTML elements display the data:
<div id="Hidden_Data"></div>
<div id="Show_Data_001"><?php echo $variable1; ?></div>
<div id="Show_Data_002"><?php echo $variable2; ?></div>
<div id="Show_Data_003"><?php echo $variable3; ?></div>
...
I tried using the data parameter as suggested here:
https://stackoverflow.com/a/8480059/498596
But I couldn't fully understand how to load all the variables every 5 seconds and call them on the index page.
Today the GetData.php page just returns $variable1 = X; $variable2 = Y and so on.
UPDATE
For some reason the jQuery is not loading the GatData.php file and refreshing the variables.
I tried adding to "Hidden_Data" to the include('GetData.php') and then the variables are readable on the page.
If I remove this part, the page displays "variable not set" warning that suggesting that the jQuery is not loading the GetData.php script into the Hidden_Data <div>.
Try
<script>
var refreshId = setInterval(function()
{
$('#Hidden_Data').load('GetData.php', function() { // Shouldn´t this return $variables
$('#Show_Data_001').fadeOut("slow").fadeIn("slow");
$('#Show_Data_002').fadeOut("slow").fadeIn("slow");
$('#Show_Data_003').fadeOut("slow").fadeIn("slow");
$('#...').fadeOut("slow").fadeIn("slow"); });
}, 5000); // Data refreshed every 5 seconds
*/
</script>
Above is assuming, that your code returns snippet of HTML elements (Show_Data_XXX), but now that you've clarified your question above wont help you alone...
What you need to do is either in your php send back new value elements or send back your results as data and update existing elements.
Put your elements into a php Array and then send it back
data.php after sql call
$results = Array();
while($row = mysql_fetch_array($result)){
$column1 = $row['column1 ']; // change Text1 in db to Show_Data_001 in html or vice versa
$variable = $row['variable '];
$results[$column1] = $variable;
}
echo json_encode($results);
in your javascript something like this...
$.getJSON('GetData.php',function(data) {
$.each(data, function(key, val) {
$('#'+key).text(val);
});
});
I didn't put the fadeOut and fadeIn into the example, because it complicates it a bit. You could do fadeOut to all those elements before calling getJSON and the fadeIn as the results pouring in. Hope this helps
First of all, make sure you have correct respond from server, just like this:
//We won't use load() to load content for now
window.setInterval(function(){
$.ajax({
url : "path_to_your_php_script.php",
type : "GET",
beforeSend: function(){
//here you can display, smth like "Please wait" in some div
},
error : function(msg){
//You would know if an error occurs
alert(msg);
},
success : function(respondFromPHP){
//Are you getting distinct results every 5 sec?
alert(respondFromPHP);
return;
//if respondFromPHP contains data you want
//ONLY THEN, add some effects
}
});
}, 5000);
The only difference between this approach and yours, is that, you can handle errors and make sure you are getting data you want.
Can you show me the code of GetData.php?
Rather than using Jquery.load you can actually get the page with $.post or $.get and format your results from GetData.php to Json or xml you can easily map it to your javascript.
Using $.post it will allow you to have a callback after getting the value from GetData.php and you can check it if it's working right or not. If it gets a data from your GetData.php then you can populate it to your DIV elements.
You can check more information regarding POST and GET here:
http://api.jquery.com/jQuery.post/
I've got this lines of code that, when the user clicks on the link, the page should scroll down to the respective anchor.
Turns out that it only works with the first link. The others just fire this exception
Uncaught TypeError: Cannot read property 'slice' of undefined
Here's the code
jQuery
$(document).on('click','#scrollTo',function(){
var to = $(this).attr('class');
//alert(to);
//This allways print the correct class name
$(window).scrollTo('div #'+to,'1000');
});
PHP
<ul id="source">
<?php
$sourceRCS = $source->getAllSources();
foreach($sourceRCS as $src)
{
echo '<li data-value="'.$src->name.'">'.$src->name.'</li></a>';
}
?>
</ul>
foreach($sourceRCS as $src)
{
echo '
<div class="custom-label-src">
<div id="'.$src->name.'" class="span12 label-title-src">
'.$src->name.'
</div>
</div>';
}
What am I doing wrong?
Thank you in advance
ID's are supposed to be unique, but you repeat #scrollTo. Try using a CSS class as your target instead.
var to = $(this).attr('class');
$(window).scrollTo('div #'+to,'1000');
You are selecting a class and assigning it to "to". Then you take the class and convert it into an ID in the next line.
Your selector should be like this:
var to = $(this).attr('class');
$(window).scrollTo('div .' + to,'1000');
Html Id's have to be unique. Like previously suggested, try using classes instead. Also, try capturing the event target and scrolling to it:
$(document).click(function(evt){
var target = evt.target;
$(window).scrollTo(target, 1000);
});
However, this will scroll to everything that a user clicks on. A better solution is to set up click event handlers on only the anchor tags that you want to scroll to:
$("#source a").click(function(evt){
evt.preventDefault();
var target = $(evt.currentTarget);
$(window).scrollTo(target, 1000);
// More code here...
});
In a PHP page i have several rows of one table like this
echo '<tr><td>Click</td></tr>';
The $id is dynamically generated from a database
So I want to define the function in jQuery but to pass the parameter to the jQuery function.
For each button I click there will be another parameter passed
Why not use the ID as an identifier for the link like this:
Click me
In jQuery you can bind to the onclick event like this:
// Execute on load
$(document).ready(function(){
// Bind to click
$('a.myjquerylink').click(function(){
// Get the id
var id = $(this).attr('id');
// Do something with the id.
doSomething(id);
});
});
What exactly do you want to do ?
Here's a sample function (it's not using jQuery!) to alert the user that the linked has been pressed and to stop propagating the event, so that it doesn't jump to another page on click
<script type="text/javascript">
function myFunction( param ) {
alert('The button with the id ' + param + ' has been pressed!');
return false;
}
</script>
Well in a dirty way you can assign your id's in rel tag like this:
echo '<tr><td>Click</td></tr>';
than you can search for mybutton class in jquery an add events to it:
$("a.mylink").click(function(){
alert($(this).attr('rel'));
});
So in this case $(this).attr('rel') should be your ID.
As other poster started saying, bind a function to an event. Say you assign a css class to your a tags to make it easier:
echo '<tr><td><a class="specialLinks" href="#" onclick="myFunction('.$id.')">Click</a></td></tr>';
Then you would bind to your class like this:
$('.specialLink').bind('click', function() {
this.preventDefault();
alert($(this.attr("id"));
});
you need to modify your html a bit:
echo '<tr><td><a class="someclass" href="#" id='".$id.'">Click</a></td></tr>';
then you can call it by it's class in JQuery and do what you want:
"$(this)" will be a reference to the clicked item.
$(".someclass").live('click',function(e){ e.preventDefault(); alert($(this).text())});
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.