How I can do a foreach or similar in jQuery? I need that when the user clicks in the <span>, add the class inactive to all <div>s with the vote active class in the <ul>.
I've tried with the .each method, but it doesn't work.
I have this HTML:
<ul class="suggestions inactive">
<li id="s2">
<div class="id">2</div>
<div class="vote inactive">
<span class="up"></span>
<span class="down"></span>
</div>
<div class="text">test2</div>
<div class="rating">2</div>
</li>
<li id="s3">
<div class="id">3</div>
<div class="vote active">
<span class="up"></span>
<span class="down"></span>
</div>
<div class="text">test3</div>
<div class="rating">0</div>
</li>
</ul>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="script.js"></script>
And this script:
$(document).ready(function(){
var ul = $('ul.suggestions');
// Listening of a click on a UP or DOWN arrow:
$('div.vote span').live('click',function(){
var elem = $(this),
parent = elem.parent(),
li = elem.closest('li'),
ratingDiv = li.find('.rating'),
id = li.attr('id').replace('s',''),
v = 1,
ul2 = elem.closest('li').parent();
// If the user's already voted:
if(parent.hasClass('inactive')){
return false;
}
if(ul2.hasClass('inactive')){
return false;
}
//If the user's already voted, add following class
parent.removeClass('active').addClass('inactive');
ul2.removeClass('active').addClass('inactive');
if(elem.hasClass('down')){
v = -1;
}
// Incrementing the counter on the right:
ratingDiv.text(v + +ratingDiv.text());
// Turning all the LI elements into an array
// and sorting it on the number of votes:
var arr = $.makeArray(ul.find('li')).sort(function(l,r){
return +$('.rating',r).text() - +$('.rating',l).text();
});
// Adding the sorted LIs to the UL
ul.html(arr);
// Sending an AJAX request
$.get('ajax.php',{action:'vote',vote:v,'id':id});
});
You don't need .each() here at all.
Why? Because jQuery's selectors wonderfully select everything of a single selector type. $('p') selects every p in your HTML.
You should use
$(this).parent().addClass('active').removeClass('inactive');`
from within the scope of the
$('div.vote span').live('click',function() { ... } );
Also, remember that .live() is deprecated in jQuery 1.7+.
Are you sure you really want to add that class to ALL elements in the HTML? If so, I guess I would just do this:
$("div").addClass("inactive");
You do not need each for adding class to multiple elements. Just select them and apply addClass():
jQuery('div.vote.active').addClass('inactive');
If you insist on using .each(), then it really works. Just use it properly:
jQuery('div.vote.active').each(function(){
jQuery(this).addClass('inactive');
});
Did it help?
Related
So, I have the following php and js markup:
<div class="top" data-id="<?php echo $id; ?>">
<div class="middle">
Click
</div>
<div class="info"> <!--Note that I am targeting a child div -->
<div class="name">
Steve
</div>
</div>
</div>
Then for my js:
jQuery(document).on( 'click', '.middle', function(e) {
var my_id= jQuery(this).parent('.top').data("id");
});
At this point, when the middle div is clicked, the js var my_id is equal to the data_id of its top parent div (with .top).
Now, I want to save another div as below (simple html).
var my_name = $('.name').html();
How do I target the specific .name class within the specific `data-id' div?
You could use the .siblings() method to select all the sibling elements of .middle, and then use .find() to find any descendant .name elements:
jQuery(document).on( 'click', '.middle', function(e) {
var my_id= jQuery(this).parent('.top').data("id");
var my_name = jQuery(this).siblings().find('.name').html();
});
Use the parent and find methods.
var current;
$(document).on( 'click', '.middle', function(e) {
var my_id= $(this).parent('.top').data("id");
current = $(this).parent().find('.name');
console.log($(current).html());
});
Edit: John Crozier's answer is more complete. Beat me to it :)
<div class="textbox-fill-mid">
<div style="display:none;" class="bbit-cs-id">171</div>
<div style="cursor:pointer;" >adad</div>
</div>
<div class="textbox-fill-mid">
<div style="display:none;" class="bbit-cs-id">11</div>
<div style="cursor:pointer;" >adad</div>
</div>
<div class="textbox-fill-mid">
<div style="display:none;" class="bbit-cs-id">41</div>
<div style="cursor:pointer;" >adad</div>
</div>
my url : localhost/pr1/ev.php?eid=41
if(isset($_GET['eid']))
{
echo "<div id='notifi_event_id'>".$_GET['eid']."</div>";
}
using jquery
var notifi_event_id=$('#notifi_event_id').text(); // having 41
I know that all elements with different values are located into .bbit-cs-id, but I don't know how to find any of the .bbit-cs-id having 41 or not ,
Hope this also will help you
var is41=false;
$('.bbit-cs-id').each(function(i,data){
if($(this).text()=='41')
is41=true;
});
alert(is41);
http://jsfiddle.net/ilaiyaraja/AE9zy/1/
To find an element containing a specific text value, you need to use filter():
var notifi_event_id = $('#notifi_event_id').text(); // = 41
var $bbit = $('.bbit-cs-id').filter(function() {
return $(this).text() == notifi_event_id;
});
// you can then do something with the matching element:
$bbit.addClass('foo');
Example fiddle
You can use this syntax to access each div :
var cases = $('div.bbit-cs-id').each(function()
{
// You access each object with : $(this)
// So you can access Text with the following line :
console.log($(this).html());
});
use jQuery :contains operator to look for text content:
if($('.bbit-cs-id:contains(41)').length){
console.log($('.bbit-cs-id:contains(41):first')); //print the first element.
//update the parent or the sublink.
$('.bbit-cs-id:contains(41):first').next().css({color:'red'});
$('.bbit-cs-id:contains(41):first').parent().css({border:'1px solid gray'});
}
Fiddle
Note:
it if this div is just to hold the ID of something ... why not use data attribute to the container?:
<div class="textbox-fill-mid" data-id="41">
<div style="cursor:pointer;" >adad</div>
</div>
<script>
$('.textbox-fill-mid[data-id=41]');
</script>
Here is my html for my populated listview. I have the link grabbed from the php script aswell. Where would i put the page slide function on click event. It wont allow me to but html in the script
<div data-role="content">
<script type="text/javascript">
$(document).on("pagebeforeshow", "#index1", function() {
$(function(){
var items="";
$.getJSON("check-events.php",function(data){
$.each(data,function(index,item)
{
items+="<li><a href="+item.col1+"?eventid="+item.id+">"+item.col2+"<p></p><p>"+item.col3+"</p></li>";
});
$("#contacts").append(items);
$("#contacts").listview("refresh");
});
});
});
</script>
<div data-role="fieldcontain">
<ul id="contacts" data-role="listview" data-divider-theme="b" data-inset="true">
<li data-role="list-divider" role="heading">
List view
</li>
</ul>
</div>
Where would i add this piece this code. It keeps producing an error when i add it like this
items+="<li><a href="+item.col1+"?eventid="+item.id+" data-transition="slide">"+item.col2+"<p></p><p>"+item.col3+"</p></li>";
Any ideas
Working solution
php
$data = array();
while($rowa = mysql_fetch_array($a, MYSQL_ASSOC))
{
$row_array['id'] = $rowa['eventid'];
$row_array['col1'] = "index.html";
$row_array['col2'] = $rowa['eventname'];
$row_array['col3'] = date("D jS F Y",strtotime($rowa[enddate]));
$row_array['col4'] = "slide";
array_push($data,$row_array);
}
echo json_encode($data);
}
changed html
items+="<li><a href=\""+item.col1+"?eventid="+item.id+"\" data-transition=\""+item.col4+"\">"+item.col2+"<p></p><p>"+item.col3+"</p></li>";});
You need to escape your quotes when putting in the variables (\")
items+="<li><a href=\""+item.col1+"?eventid="+item.id+"\" data-transition=\""slide"\">"+item.col2+"<p></p><p>"+item.col3+"</p></li>";
But, on a side note, you should be letting JQuery create your elements for you. See: https://stackoverflow.com/a/4158203/1178781
So, I understand that mixing javascript into HTML is bad, even in head. But lets see this code (I want to remove items the from list)
.
.
.
<div>item1 delete me<br />
<div>item4 delete me<br />
<div>item5 delete me<br />
.
.
.
This list is generated by PHP. deleteThisItemById() is in an external .js file. Is this still considered bad?
If so, what would be a canonical solution? jQuery is acceptable, as is raw javascript.
$(function() {
$('a#my_id1').click(function() {
var myId = $(this).attr('id');
return deleteThisItemByID(myId);
});
});
<div>
item1
<a id="my_id1" href="#">delete me</a>
</div>
By the way, your HTML is invalid. You have improperly nested div tags.
Simple... give the item you want removed a class or id (only use an id if its only one item)
<div>item1 <a href="#" class='deleteMe'>delete me</a><br /></div>
<div>item4 <a href="#" class='deleteMe'>delete me</a><br /></div>
<div>item5 <a href="#" class='deleteMe'>delete me</a><br /></div>
Then target the elements with jQuery
$('.deleteMe').on('click', function(event) {
$(this).remove();
});
Note... if you wanted to remove the entire div, use this selector:
$('.deleteMe').closest('div').on('click', function(event) {
$(this).remove();
});
you could use addEventListener to do this.
Then no js-code will be in your html:
var elems = document.querySelectorAll("div.removable");
for(var i=0;i<elems.length;i++){
elems[i].querySelector("a").addEventListener("click",function(e){
var toRemove = this.parentNode;
var parent = toRemove.parentNode;
parent.removeChild(toRemove);
},false);
}
however, I iterate over the divs, so I added a class for this:
<div>
<div class="removable">item1 delete me</div><br />
<div class="removable">item2 delete me</div><br />
<div class="removable">item2 delete me</div><br />
</div>
Have a look at this fiddle
I like to stash id's and similar metadata in "data-" attributes on the dom elements that represent those objects.
In this case I will usually use a similar setup
<ul class="posts">
<li class="post" data-post="####">
<p>content...</p>
<ul class="actions">
<li>
<a class="delete">delete</a>
</li>
</ul>
</li>
</ul>
Then in an .js file included at the bottom of the page:
$('.posts').on('click', '.actions .delete',
function() {
// which post should be deleted?
var $post = $(this).closest('.post');
// remove the DOM element
$post.remove();
// some sort of ajax operation
$.ajax({
// url, dataType, etc
data: { post_id: $post.data('id') }
});
});
This one handler will apply to all ".action .delete" elements in the main list, meaning that if you want to add a loader or pagination that uses ajax to modify or add times to the list, the one event handler will still work wonderfully.
I have this div tags :
<div id="target-share">
<span class="to-admin">Admin</span>
<ul id="select-shareto">
<li data-val="0-1">
<span class="to-Finance">Finance</span>
</li>
<li data-val="1-1">
<span class="to-admin-private">Admin Private</span>
</li>
<li data-val="1-0">
<span class="to-ceo">CEO</span>
</li>
<li data-val="0-0">
<span class="to-ceo-private">CEO Private</span>
</li>
</ul>
<input id="shareto" type="text" value="0-1" name="shareto">
</div><!-- #target-share -->
and this JavaScript :
<script type="text/javascript">
$(document).ready(function($) {
$('ul li').click(function() {
$('input#shareto').val($(this).data('val'));
});
});
</script>
that JavaScript actually works when I'm using it with that div alone. but when I put it on my full code, that JavaScript doesn't work. I think that because there are more than one UL and LI tags on my code.
Now, the question is... how to apply that Javascript so that it can works ONLY for that div, even though there are other UL and LI tags.
Just use this instead targeting the div first then its contents
$('#target-share ul li')
JavaScript (not just Jquery) is all about scoping:
$('ul li').click(function() {
Causes that click to bind to every li in a ul so what you wanna do is scope the click down to a specific area of your page or set of elements across the page.
To scope it down to a specific element the best idea is to use a id like so:
$('#target-share ul li')
But to scope it down to a number of elements it is better to use a class like:
$('.target-share ul li')
Edit:
Also on() could be a good replacement here for click but it depends on where the HTML is being sourced and how it is being used, but thought I would make you aware of that function in case you didn't already know about it.
Select those ul li that have your data-val attribute:
$(function($) {
$('ul li[data-val]').click(function() {
$('input#shareto').val($(this).data('val'));
});
});