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.
Related
I am failing hardcore with describing this but here it goes..
I have home.php, pretty much just:
<body>
<div id='leftColumn'>
<?php include ('includes/roomQuery.php')
</div>
</body>
Now,
roomQuery.php echos my sql column 'room_name' from table 'rooms' as follows:
echo "<td>$roomName</td>";
Any of the room links will take me to room.php and populate the page with more queries respective to $roomName via $_GET.
room.php is basically:
$get = $_GET['room'];
$query
while($row = $result->fetch_assoc()){
echo $query
This is working perfectly for what it is.
====================================
however, I am trying to make my site flow better, and have been trying out the jQuery .load function. So far I have changed roomQuery.php to:
echo "<td><button>$roomName</button></td>";
here is my jQuery to replace home.php #page with room.php #page:
$(document).ready(function(){
$("button").click(function(){
$("#page").load("room.php #page",function(responseTxt,statusTxt,xhr){
if(statusTxt=="success")
alert("Success");
if(statusTxt=="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
});
});
});
When I click any of the buttons that roomQuery.php spits out, it replaces #page perfectly but I cannot grasp how/if I can send $_GET['room'] to room.php so that when #page is loaded, the information is still respective to the room I clicked on. If I change jQuery to
$("#page").load("room.php?room=CL%20124 #page"
Then #page is populated with the data specifically respective to room CL 124. Is it possible to post the button text that is output from roomsQuery.php to room.php #page when the button is clicked?
Yes, you can pass data into the .load() call as the second parameter.
Firstly, you need to work out how to get the room ID from the DOM into your jQuery call, maybe you could use a data attribute on the button element like this:
<button data-room-id="123">Click me</button>
Then use jQuery like this:
$("button").click(function(){
// define your room ID here, however you do it
var your_room = $(this).data('room-id');
$("#page").load(
"room.php #page",
{
room: your_room
},
function(responseTxt,statusTxt,xhr){
if(statusTxt=="success")
alert("Success");
if(statusTxt=="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
}
);
});
Edit: just noticed that you might actually be using the button's value as your room ID, if so, use this definition:
var your_room = $(this).val();
If you're expecting spaces or non-alpha numeric characters in this value, you might want to consider URL encoding it before you send it.
I need a dynamic form which is supposed to work like this:
When user press "ADD" button, appear a new ..<.div> DOM to select a package.
Depending on the package, the row must change color (by adding/removing some classes).
But I can't get it working. Here is my HTML:
<button onclick='addDay();'>
<div class='content'>
</div>
My Javascript:
//FUNCTION 1: LOAD AJAX CONTENT
function addDay()
{
baseUrl = $('input#helper-base-url').val();
//Set caching to false
$.ajaxSetup ({
cache: true
});
//Set loading image and input, show loading bar
var ajaxLoad = "<div class='loading'><img src='"+baseUrl+"assets/images/loading.gif' alt='Loading...' /></div>";
var jsonUrl = baseUrl+"car/add_day/"+count;
$("div#loading").html(ajaxLoad);
$("div#content").hide();
$.getJSON(
jsonUrl,
{},
function(json)
{
temp = "";
if(json.success==true)
{
temp = json.content;
}
//Display the result
$("div#content").show();
$("div#content").html($("div#content").html()+temp);
$("div#loading").hide();
});
}
//FUNCTION 2: MODIFY AJAX CONTENT
$("#content").on("change", "select.switch", function (e) {
e.preventDefault();
//Get which row is to be changed in background's color
id = this.id;
id = id.substr(6);
//Add class "package1" which change row's background color
row = "row"+id;
row.addClass('package1');
});
My PHP
function add_day($count)
{
$temp = "<div class='row".$count."'>
<select id='switch".$count."' class='switch'>
<option value='1'>Package 1</option>
<option value='2'>Package 2</option>
</select>
</div>";
$result = array(
'success' => true,
'content' => $temp,
);
$json = json_encode($result);
echo $json;
}
PS. The form is not as simple as this but to make the problem solving easier, I remove the details. But I can't seem to change the class on the fly. Do we have a solution or a good work around here?
Edit 1:
Sorry I didn't make myself clear before. I had no problem with getting the id or variable (it was okay, when I alert it the right value comes out - but after I add the class, no color changes is seen). I run it:
a. On button click, load Ajax content.
b. Ajax content (which results contains a ) loaded successfully.
c. FAIL: On change, add class "package1" to the div row. (So, I had no problem with getting the right id or class name. When I alert the variables it gives the right result, BUT the color doesn't change. I can't check whether class is successfully added or not.)
$("#content").on("change", "select.switch", function (e) {
e.preventDefault();
$('.row' + $(this).attr('id').replace('switch', '')).addClass('package1');
});
Assuming that everything else is ok
//Get which row is to be changed in background's color
id = this.id;
id = id.substr(6);
//Add class "package1" which change row's background color
row = "row"+id;
row.addClass('package1');
This is the problem. To get the attibute id you have to do
var id = $(this).attr('id').substr(6);
You have to use $(this) and not this by the way to use all of jQuery functionalities.
Same below
$(row).addClass('package1');
So, full code:
//Get which row is to be changed in background's color
var id = $(this).attr('id').substr(6);
//Add class "package1" which change row's background color
$('.row'+id).addClass('package1');
Changing the class to id solved the problem (using #row0 instead of .row0). Sorry and thank you for your time :)
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 may have misunderstood the purpose of PHP here. But I want to do the following:
I have a PHP function, and I call it from HTML, e.g.
<BODY>
<DIV id='A'>
<?php emit("hello1"); ?>
</DIV>
<DIV id='B'>
<?php emit("hello2"); ?>
</DIV>
</BODY>
And I want to know, within the function, which DIV it was called from.
e.g.
<?php function emit($txt){
echo "$txt";
echo "from DIV id $DIVID"
}
?>
And I want it, obviously, to print
hello1 from DIV id A
hello2 from DIV id B
Is there any way of finding the "current" DIV's ID?
Yes, you have misunderstood the purpose of PHP.
PHP is a server side programming language, it does not run on the HTML page, but before the HTML gets loaded on to the browser.
The task that you are trying to do can be done from JavaScript if interested. I will give an example of jQuery:
var emit = function(el, txt) {
var id = el.attr('id');
el.html(txt+" from DIV id "+id);
}
Now call using
emit($("#a"), "hello1");
Same can be done from JS in the following way
var emit = function(el, txt) {
el = document.getElementById("el");
id = el.getAttribute('id');
el.innerHTML(txt+" from DIV id "+id);
};
Use like:
emit("a", "hello1");
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.