can't get the id using .each - javascript

I am working on the tabs page... I am trying to get the id's of li from the loop and then hide it. the id's is not found.
<ul>
<li id="Page1" class="tab">Page2</li>
<li id="Page2" class="tab">Page2</li>
</ul>
jquery code:
$(".tab").click(function() {
var thisclick = $(this).attr("id");
var links = $(this).parent();
$(links).each(function() {
$("#PG_" + $(this).attr("id") ).hide();
});
$("#PG_" + thisclick).show();
});

If I understand your problem correctly you have some corresponding elements on the page that should be shown only if underlying link has been clicked. If that's the case then this would work:
$(".tab").click(function() {
var thisclick = $(this).attr("id");
var links = $(this).parent().children();
$(links).each(function() {
$("#PG_" + $(this).attr("id")).hide();
});
$("#PG_" + thisclick).show();
});
http://jsfiddle.net/gdc88/4/

because the links variable is a pointer to the ul element:
var links = $(this).parent();
change to this one may help you:
$(".tab").click(function() {
var thisclick = $(this).attr("id");
var links = $(this).parent();
$(links).find("li").each(function() {
$("PG_" + $(this).attr("id") ).hide();
});
$("PG_" + thisclick).show();
});
Also, you can use
$(links).children("li").each( //etc
OR
$("li", links).each( //etc

At first glance, you want jQuery to query for a Nodename called PG_Page1 for instance, which most likely, will have no result. Unless you got tags like
<PG_Page1></PG_Page2>
somewhere on your page. So my guess is, you either forgot the prefix the string with a . for a classname, or a # for an id.
And by the way, you can just access this.id instead creating a jQuery wrapper object and finally call attr() on it.

Do you miss # in the selector?
$("#PG_" + $(this).attr("id") ).hide();

With a small class addition to your HTML, you can simplify your jQuery. Like so
<ul>
<li id="Page1" class="tab">Page1</li>
<li id="Page2" class="tab">Page2</li>
</ul>
<div id='PG_Page1' class="page"> content from page 1 here </div>
<div id='PG_Page2' class="page"> content from page 2 here </div>
jQuery
$(".tab").click(function() {
var thisclick = $(this).attr("id");
$('div.page').each(function(){
$(this).hide();
$("#PG_" + thisclick).show();
});
});
Example: http://jsfiddle.net/jasongennaro/fZNUH/

Related

Hide same elements in a list

I have a problem I want to solve with jQuery. In a list, I want to check if two items have the same text, and if so I want to delete the second one.
I am not really sure how to go about it.
The markup is simple, kinda like this
<ul>
<li>Text1</li>
<li>Text2</li>
<li>Text1</li>
<li>Text3</li>
<li>Text3</li>
<li>Text4</li>
<ul>
I cannot use an active/inactive class because this list is dynamic and I don't know in advance how it's going to be populated.
Any idea?
$.inArray for a tmp array would work.
$(document).ready(function(){
var tmparr = [];
$('.list li').each(function(i,item){
if($.inArray($(this).text(), tmparr) >= 0){
$(this).remove();
}else{
tmparr.push($(this).text());
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list">
<li>Text1</li>
<li>Text2</li>
<li>Text1</li>
<li>Text3</li>
<li>Text3</li>
<li>Text4</li>
<ul>
You can achieve this e.g. like this:
var unique = {};
$('li').each(function() {
var txt = $(this).text();
if (unique[txt])
$(this).remove();
else
unique[txt] = true;
});
Fiddle
As explanation: unique is initialized as object. While each() iterates over all li elements, the if (unique[txt]) is true in case it was previously set to true for the text of the li currently processed. In this case the current li will be removed. If not, unique[txt] for the text of the current li is set to true and added to unique. As it might not be clear what unique finally contains: { Text1=true, Text2=true, Text3=true, Text4=true }
You will need to iterate over your li elements and store their text in an array. If the text for the ith element is already in the array, skip it. Once you have an array of unique text strings, remove all li elements and generate new ones from the information in your array.
http://jsfiddle.net/k255o52e/1/
$('ul li').each(function () {
var txt = $(this).text();
// finds all LI that contain the same text
// excludes the first element
var $li = $('li:contains("' + txt + '"):not(:first)');
// and removes the other
$li.remove();
})
UPDATE:
$('ul li').each(function () {
var txt = $(this).text();
var $li = $('li:contains("' + txt + '"):not(:first)').filter(function(index)
{
return $(this).text() === txt;
});
$li.remove();
})

Press a unique button do the actions

So as I started using JavaScript and jQuery, I have a question with unique div.
Is is possible in the JavaScript to make a unique div name then do the action onclick?
http://jsfiddle.net/agmr2ytd/4/
Example HTML:
<div id="favoriteXBSbQG6fNlObroDG4ML2l9VRO/yNpvIFxL0Qjr6bP2A=">
Me
</div>
<div id="favoriteakkbN3eo8h0Q7S4ouHqMX7cU9vNLNKw3llO/PK0e9qI=">
Me 2
</div>
JavaScript:
$(function() {
$('.favorite').click(function() {
var element = $(this);
var verify = element.attr("id");
alert(verify);
$('#favorite'+verify).hide();
});
});
When I press a first a from div I wanna get the id value as a alert and hide it.
You need to set class = favorite to your divs, then this is working:
DEMO
jQuery / javascript:
$(function() {
$('.favorite').click(function() {
var element = $(this);
var verify = element.attr("id");
alert(verify);
var tohide = document.getElementById(verify);
tohide.style.display = 'none';
});
});
HTML:
<div id="favoriteXBSbQG6fNlObroDG4ML2l9VRO/yNpvIFxL0Qjr6bP2A=" class="favorite">
Me
</div>
<div id="favoriteakkbN3eo8h0Q7S4ouHqMX7cU9vNLNKw3llO/PK0e9qI=" class="favorite">
Me 2
</div>
Your selector is wrong, for attributes ^= means "attribute value starts with":
$(function() {
$('[id^=favorite] a').click(function() {
var element = $(this);
var verify = element.attr("id");
alert(verify);
$('#favorite'+verify.replace(/([ #;?%&,.+*~\':"!^$[\]()=>|\/#])/g,'\\$1')).hide();
});
});
Example Fiddle <-
Your ID has to be escaped, used this answer for solution.

Click based upon value of hash on url

I'm new to working with JS/jQuery, I've been currently trying to figure out how to make this work, by trying many different ways that I've found here and on different sites, and am unable to get this working.
I have a website that has tabs, that changes a div's content when the click on the buttons in the menu. This all works fine, but I want to be able to link to each separate "page" using hash tags example.com/#tab-1
HTML:
<div class="tabWrapper">
<div class="tabContent">
<div class="label">TAB 1</div>
<?php include 'tab1.php'; ?>
</div>
<div class="tabContent">
<div class="label">TAB 2</div>
<?php include 'tab2.php'; ?>
</div>
tabWrapper looks like this after being generated
<div class="tabWrapper">
<ul class="tabs">
<li class="tab-1">TAB 1</li>
<li class="tab-2">TAB 2</li>
</ul>
JS :
// Generate tab navigation
if ($('div.tabWrapper').length != 0)
{
$('div.tabWrapper').each(function()
{
// Prepare tab output
var printTabs = '<ul class="tabs">';
var tabContent = $(this).find('.tabContent');
var tabCount = tabContent.length;
$(tabContent).each(function(key)
{
// Hide tab if it is not the first
if (key != 0)
{
$(this).hide();
}
// Get label for tab
var label = $(this).find('.label').text();
// Use a number if no label was given
if (!label)
{
label = 'Tab ' + (key + 1);
}
// Add id to tab content
$(this).addClass('tab-' + key);
printTabs+= '<li class="tab-' + key + '">' + label + '</li>';
});
// Add tabs
$(this).prepend(printTabs + '</ul>');
$(this).find('li:first').addClass('active');
});
}
// Handle click on tabs
$('.tabWrapper').delegate('ul.tabs li', 'click', function()
{
// Deny click on active element
if ($(this).is('.active'))
{
return false;
}
// Get tab id
var id = $(this).attr('class').split('-');
id = id[1];
// Display and animate new tab content
var parent = $(this).parent().parent();
parent.find('ul.tabs li').removeClass('active');
$(this).addClass('active');
parent.find('.tabContent').hide()
parent.find('.tab-' + id).animate({ opacity: 'show' }, animationSpeed);
});
Here is what I was trying to add, which I don't think is correct
function hash() {
if(window.location.hash){
var hash = window.location.hash.substring(1);
$("." + hash).click();
}
}
which I added in the js file just above
$('.tabWrapper').delegate('ul.tabs li', 'click', function()
I'm not sure how far I'm off with that code, as it doesn't seem to work at all. I just want it to see if there is a hash tag in the url, and if there is then run the click function to change the content.
I hope I explained what I was looking for clear enough. I'd very much appreciate any help with this.
Thank you.
UPDATE:
I updated the code with setInterval as per chiliNUT's suggestion, however it still doesn't appear to be working.
setInterval(hash,1000);
function hash() {
if(window.location.hash){
var hash = window.location.hash.substring(1);
$("." + hash).click();
}
}
UPDATE 2:
Still unable to get this working, anyone able to help?
Thanks.
My tip is using anchor tags as well.
Link
That will open example.com#tab1
The control on page load:
$( document ).ready(function() {
if(window.location.hash == "#tab1"){
$("#someId").click();
}
});
Why not just use anchor tags?
Button to open tab 1

jQuery select href values in nested divds

Although I found several answers to select a href attribute neither of them is working for me. Maybe someone can help.
The html is as follows
<div class="galleryitem">
<div class="itemlink">
Page
</div>
<div class="itemimg">
test1.png
</div>
</div>
<div class="galleryitem">
<div class="itemlink">
Page 1
</div>
<div class="itemimg">
test2.png
</div>
</div>
Now i want to geht all the attribute values in the hrefs and tried with
$('.galleryitem').each(function() {
var link = $(this).children('itemlink a').attr('href');
var img = $(this).children(".itemimg a").attr("href");
//jQuery("#somediv").append("<a href='" + link + "'><img class='cloudcarousel' src='" + img + "'/></a>");
});
I dont know why link and img are undefined. Even $(this).children('.itemlink a') is undefined.
Can anyone help on this?
Try with find
$('.galleryitem').each(function() {
var link = $(this).find('itemlink a').attr('href');
var img = $(this).find(".itemimg a").attr("href");
//...
})
you want to sure the .find() method instead of .children which only grabs the immediate descendants. (you also have a small error missing the period in itemlink)
var link = $(this).find('.itemlink a').attr('href');
var img = $(this).find(".itemimg a").attr("href");
should work for you, and here is a fiddle: http://jsfiddle.net/hQeu3/
the reason .children doesn't works is that there are no immediate descendents that match this selector '.itemlink a'. jQuery grabs the divs (".itemlink"), and then tries to filter to the selector, which fails in this case. it is essentially equal to
$(this).children().filter('.itemlink a'); //won't work!
if you want to use children you could do
$(this).children('.itemlink').children("a").attr('href');
You could do as follows:
$('.galleryitem').each(function() {
var link = $('.itemlink > a', this).attr('href');
var img = $('.itemimg > a', this).attr('href');
});
which take into account that .itemlink and .itemimg are a direct parent of the <a> element.

issues with replacing a div with a div dynamically

I have created an html page, (template if you will) so what I would like to do is to leave the page all on it's own and use AJAX / jQuery to propagate the div elements with other external html pages.
Is this possible ?
I have been checking around and I have yet to find the solution.
Here is a snippet of my nav list...
<div>
<ul>
<li id="n-c"><span class="dir">Cosmo</span>
<ul id="switcheroo">
<li class="first">Special</li>
<li>Mineral</li>
<li>Lateral</li>
<li>Tangent</li>
</ul>
</li>
</ul>
</div>
In my content section I have added a
<div id="contentSwap"></div>
I tried this:
$("ul #switcheroo li a").click(function(event) {
var $parent = $(this).parent();
$parent.addClass("selected").siblings().removeClass("selected");
var href = $(this).attr('href');
$.get(href, function(data) {
$('#contentSwap').html(data);
});
event.preventDefault();
return false;
});
to no avail, can someone help me?
WDH
in the end I ended up using the simplest form to achieve my result.
<script type="text/javascript">
$(document).ready(function() {
$("#switcheroo").click(function(event){
$('#contentSwap2').load('pg2.html');
});
});
$(document).ready(function() {
$("#switcheroo2").click(function(event){
$('#contentSwap3').load('pg3.html');
});
});
</script>
... and so on ...
And ultimately swapping the div id with the one that had content already, instead of using an empty tag.
WDH
I appreciate all your insight #abdullah.abcoder #ShankarSangoli and #John Hartsock
When you get the html response in the get callback it will have all the tags starting from html, head body etc. Either you will have to make sure you only send the required markup from the server or parse the markup and and get only the markup that you want to append into contentSwap div.
The other approach is to use iframe, set the iframe source to href, onload of iframe find the required element, get the markup and then append it to contentSwap div.
$("ul #switcheroo li a").click(function(event) {
var $parent = $(this).parent();
$parent.addClass("selected").siblings().removeClass("selected");
var href = $(this).attr('href');
var dIf = $("#dummyIframe");
if(dIf.length == 0){
$(document.body).append('<iframe id="dummyIframe" style="display:none;"></iframe>');
dIf = $("#dummyIframe").onload(function(){
var iFrameContent = $("#dummyIframe").contents();
$('#contentSwap', window.parent.document)
.html(iFrameContent.find('#someDivIdOrAnyOtherSelector').html());
});
}
dIf[0].src = href;
event.preventDefault();
return false;
});
$("ul #switcheroo li a").click(function(event) {
var $parent = $(this).parent();
$parent.addClass("selected").siblings().removeClass("selected");
var href = $(this).attr('href');
$('#contentSwap').load('' + href + ''); //$('#contentSwap').empty().load(''+ href +''); you may use this for make your `#contantSwap` empty and then append contents to it
event.preventDefault();
return false;
});
I hope this will works
Assuming your data is HTML, then you can do the following using jQuery replaceWith():
$('#contentSwap').replaceWith(data);
Also, you may want to only import the portion of the HTML from the data by doing the following:
$('#contentSwap').replaceWith($('#somedivElement', data));

Categories

Resources