php for loop not sent to jquery - javascript

I am having this problem when I have a for loop of links and I want each link to alert through jquery but only the first link is working.. What could be the problem?
<link rel='stylesheet' href='CSS/nook.css' type='text/css' media='screen, projection' />
<script type="text/javascript" src="JS/jquery-1.10.2.min.js"></script>
This is my script
<script>
$(document).ready(function() {
$("#click").click(function(e)
{
e.preventDefault();
alert("hi");
});
})
</script>
And this is my loop
<?php
for($i=0;$i<2;$i++){
echo "<a href = '' id = 'click'>a</a><br>";
}
?>

ID of an element must be unique, use class to group similar elements
<?php
for($i=0;$i<2;$i++){
echo "<a href = '' class='click'>a</a><br>";
}
?>
then
<script>
$(document).ready(function() {
$(".click").click(function(e)
{
e.preventDefault();
alert("hi");
});
})
</script>
When you use id-selector, it will return only the first element with the given id others will be ignored. So in your case the click handler will be registered to only the first element withe the id click

IDs are unique, and you should only have 1 per page. So this is wrong:
<a id="unique"></a>
<a id="unique"></a>
Instead, you need to use a class:
<a class="not_unique"></a>
<a class="not_unique"></a>
The way you access a class with jquery is with . instead of #:
$(".click")

Related

Jquery click event won't recognize elements from PHP list

When i load the list of items from MySQL using PHP,jquery event click won't recognize them. Jquery is working on all other elements on the page except the option tag which is created through for loop.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script src="js/js.js"></script>
<script>
$(document).ready(function(){
$(document).on('click', '.option', function(e){
alert('cls2 clicked');
e.preventDefault();
});
});
</script>
<select>
<?php
include "konekcija.php";
$upit="SELECT * FROM galerije group by naziv_galerije";
$rez = $connection->query($upit);
foreach ($connection->query($upit) as $r)
{
$ispis.=" <option value='{$r['id_galerije']}' class='option'>
{$r['naziv_galerije']}</option>";
}
echo $ispis;
?>

Javascript add class active when click a link after load another page?

I have a list a.href to many URL contain film.
When I click a.href, it will reload my page. I don't know how to add the class .active to the a.href current selected.
In Ajax call, it simple like this code, it's working because the page is not reloaded. But I write on PHP and using $_GET and $_POST method. So the page must be reloaded.
Have any method to add the class .active on a.href link was clicked?
<div class="btn-group listEp col-md-12">
$i = 0;
Episode:
<?php foreach($data['episodes'] as $epList) { ?>
<a class="btn btn-default" href="<?php echo $epList['href']); ?>"> <?php echo $i++; ?> </a>
<?php } ?>
</div>
$(function() {
$('#listEp').on("click", "a", function() {
$( "#listEp a:first-child" ).css("cssText", "background: #4CAF50 !important;");
$(this).addClass('active').siblings().removeClass('active');
});
});
If you don't want to reload page after click and create a custom action on this just do this:
$('#listEp').on("click", "a", function(e) {
e.preventDefault() // this will disable default action which is redirect in case of a element
e.stopPropagation() // this will stop element beeing propagated by other functions
$( "#listEp a:first-child" ).css("cssText", "background: #4CAF50 !important;");
$(this).addClass('active').siblings().removeClass('active');
});
Looks like you're targeting an ID which doesn't exist, the element has a class listEp. Try $('.listEp') instead
You can do simply like this,
$('a.btn[href]').click(function(){
$('a.btn[href]').removeClass('active');
$(this).addClass('active');
});
above code removes active class from other same elements and adds class in this element.
Add below code to that page which is rendering on reload,
$(document).ready(function(){
$('a.active.btn[href]').removeClass('active');
});

How to get button link in alert box

In below code i am trying to get button href attribute value and show it in alert box using jquery.
When i click on button because of href value(i.e. $value['3']) it will redirect to our retailer link,But by using jquery when i get button link without page refresh by using href attribute it only take first link on any button link.
Actually i wan't that particular button link without page refresh.
<html><head>
<script src="jquery-1.11.3.js"></script></head>
<script>
$(document).ready(function(){
$('.button').click(function(){
var href = $('a').attr('href');
alert(href);
})
});
</script><body>
<?php
$data=array(
array("HTC desire 210 black","Flipkart",20000,"http://www.flipkart.com"),
array("HTC desire 326 white","Snapdeal",22000,"http://www.snapdeal.com"),
array("HTC desire 516","Amazon",23000,"http://www.amazon.in")
);
foreach($data as $value)
{
?>
<input type="button" value="Get link's href value" class="button" /><br/><br/>
<?php
}
?></body></html>
Try:
$('.button').click(function(){
var href = $(this).parent('a').attr('href');
alert(href);
})
change in script
<script>
$(document).ready(function(){
$(document).on('click','.button',function(){
var href = $(this).attr('data-link');
alert(href);
})
});
</script>
change in html
<input type="button" value="Get link's href value" class="button" data-link="<?php echo $value['3']; ?>"/><br/><br/>
Try This this is work fine for me.
$(document).ready(function(){
$('.button').click(function(){
var href = $(this).closest('a').attr('href');
alert(href);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<button class="button">Google</button>
<button class="button">Yahoo</button>
<button class="button">Bing</button>
So you want to alert the href value of a link when you click on it? use preventDefault();
$(document).ready(function(){
$('a').click(function(e){
alert( $(this).attr('href') );
e.preventDefault();
return false;
})
});
Or if you want to click on a button only then
$(document).ready(function(){
$('.button').click(function(e){
alert( $(this).parent('a').attr('href') );
e.preventDefault();
return false;
})
});

Hide/show div with javascript and while loop

I am trying for hours now and for some reason i can't find a solution for my problem.
The thing is, i need something like a div thats showing up when i click on an link.
That's working so far.
But the main problem is, that i need it work within a while loop. So i can get the data dynamically into grid, but all of the php created links have the same id and all of the "to-show-divs" show up at the same time. so my question is how can i create dynamic ids or classes and how do i get them to work within javascript?
echo "<div class='grid grid-pad'>";
$db=mysql_query("SELECT * FROM work") or die (mysql_error());
while($var=mysql_fetch_array($db))
{
echo "<div class='col-1-3'>
<div class='content'>
<div id='thumb' ><img alt='$var[id]' src='$var[thumb]'/></div>
<div class='menu' style='display: none;'>$var[link]</div>
</div>
</div>";
}
echo "</div>";
<script>
$(document).ready(function() {
$('#thumb').click(function() {
$('.menu').slideToggle("fast");
});
});
</script>
You can do what the comment suggests or just make an iterator variable and concat that to the id like so:
$index = 0;
while($var=mysql_fetch_array($db))
{
echo "<div class='col-1-3' id='item_". $index ."'>
<div class='content'>
<div id='thumb_". $index++ ."' >STUFF</div>
<div class='menu' style='display: none;'>$var[link]</div>
</div>
</div>";
}
Change <div id="thumb"> to <div class="thumb"> and then use following jQuery:
$('.thumb').click(function() {
$(this).next('.menu').slideToggle("fast");
});
Otherwise you'll have multiple elements with the ID "thumb", which you shouldn't.
Since the DIV is right after the link, you can use the JQuery function next() to get the next node after the link, which is the DIV:
$(document).ready(function() {
$('#thumb').on('click', function(e) {
// prevent IE from actually executing the href of the link
e.preventDefault();
// get next node, call the toggle.
$(this).next().slideToggle("fast");
// prevent executing of the href of the link
return false;
});
});
If you have more of these "thumb" links, please us a class instead of an ID - an ID has to be unique.
Edit:
Realizing that there actually are no links but DIVs, you can skip the "prevent executing" stuff of course.

Dynamic HTML IDs (PHP, Java, and a bit of SQL)

I'm trying to create a web page which generates a series of unique DIV IDs, each displaying different content based off of the entries in an SQL table.
Each div has a "hide" and "show" button, which work independently when manually giving each div a unique name.
I can get the divs themselves to generate based on class names in PHP, which displays the divs correctly.
The problem lies in the "hide" and "show" buttons since they're controlled by JavaScript. The code is as follows:
for ($j = 0 ; $j < $rows ; ++$j)
{
for($i =0; $i < $rows2; $i++)
{
if (mysql_num_rows($ans) > 0) //check if widget table is empty
{
$widgetusr[$j] = mysql_result($ans,$j,'wname')or die(mysql_error()); //user's widget
$widgetstore[$i] = mysql_result($ans2,$i,'wname'); //store widget
if($widgetusr[$j] == $widgetstore[$i] && $widgetusr[$j] != 'Medieval Calendar') //check if user has already purchased the widget
{
echo "<div class=widget_container".$j%2 .">"; //container divs are named 1 and 0. j mod 2 should return either 1 or 0
?>
<!----Start of weather Widget--->
<!---Script for show/hide buttons weather widget--->
<script>
var widg = "<?php echo $widgetusr[$j]; ?>";
var id = "#" + widg;
$(document).ready(function(){
$("#hide1").click(function(){
$(id).hide();
});
$("#show1").click(function(){
$(id).show();
});
});
</script>
<button id="hide1">Hide</button>
<button id="show1">Show</button>
<!---End Script for show/hide buttons weather widget--->
<?php
echo "<div class = 'widget' id='$widgetusr[$j]'>
</div>
</div>
<!----End of Widget---> ";
}
}
else
{
echo "You have no widgets please visit <a href='store.php'> the store </a> to purchase some. <br/>"; //widget table is empty. Redirect to widget store.
}
}
}
?>
I tried to pass the php varriable (containing an SQL value) to JavaScript (which works successfully, I was able to print out "#financial widget" as an id name.), however neither the show, nor hide button works. The generated divs all have the correct names also.
If additional information is required please ask. I tried to be as general as possible.
You really only need one button. Change your php to render the following html
<div class="widget_container">
<button class="btn ">Hide</button>
<div class="widget">widget1</div>
</div>
<div class="widget_container">
<button class="btn">Hide</button>
<div class="widget">widget2</div>
</div>
<div class="widget_container">
<button class="btn">Hide</button>
<div class="widget">widget3</div>
</div>
and output the following Outside of the loop, ensuring jQuery is loaded:
<script type="text/javascript">
//Standar jquery doc ready event, fires when the dom is loaded
$(document).ready(function(){
//add an event listener elements with a class of "btn"
$('.btn').click(function () {
//"this" is the element click, so we find siblings of this with a class
//of "widget" and toggle its visibility
$(this).siblings('.widget').toggle();
//Change the text of the button the below is short hand for:
//if($(this).text() == "Hide"){
// $(this).text("Show");
//}else{
// $(this).text("Hide");
//}
$(this).text($(this).text() == "Hide" ? "Show" : "Hide");
});
});
</script>
Example
Some useful links:
http://learn.jquery.com/using-jquery-core/document-ready/
http://api.jquery.com/click/
http://api.jquery.com/siblings/
http://api.jquery.com/closest/
http://api.jquery.com/toggle/
http://api.jquery.com/text/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
Example with fixed height widgets: http://jsfiddle.net/bdpm4/2/
Update 2
Perhaps a better way to do it: http://jsfiddle.net/bdpm4/3/
you should use class instead of id and dont put your $(document).ready() in the loop.
HTML:
<div class="widget_container">
<button class="btn hideBtn">Hide</button>
<button class="btn showBtn">Show</button>
<div class="widget">widget1</div>
</div>
<div class="widget_container">
<button class="btn hideBtn">Hide</button>
<button class="btn showBtn">Show</button>
<div class="widget">widget2</div>
</div>
JS:
$(document).ready(function(){
$('.btn').on('click', function (evt) {
var btn = $(evt.target);
btn.siblings('.widget').toggle();
btn.parent().find('.btn').toggle();
});
});
CSS:
.showBtn {
display:none;
}
here is an example: http://jsfiddle.net/xdA4r/4/

Categories

Resources