Jquery dynamically selector - javascript

I want to select the child element of an ID that is evaluated dynamically in jquery, but the code is not working. Where do you think is the mistake?
data_id is dynamically.
$("#duplicater" + data_id + ".chat_box_right_button_collapse").toggleClass("show");

In your code there is no space between your dynamic id and class name(before dot). Please check this and compare with your one
$("#duplicater" + data_id + " .chat_box_right_button_collapse").toggleClass("show");

You can use template literals
$(`#duplicater${data_id} .chat_box_right_button_collapse`).toggleClass("show");

If your child element is the element with a class of chat_box_right_button_collapse, then try with a space for the CSS selector :
$("#duplicater" + data_id + " .chat_box_right_button_collapse").toggleClass("show");
If your child element is a direct child, you can also use the > selector :
$("#duplicater" + data_id + " > .chat_box_right_button_collapse").toggleClass("show");

Related

Appending ID without replacing original

I'm trying to append an ID to div elements, but it seems if there is already an ID it replaces the existing. I'm at a loss.
$(document).ready(function(){
$("div").each( function(i){
$(this).attr({ id: " num_" + ++i });
})
});
You can do it like below:
$(document).ready(function(){
$("div").each( function(i){
$(this).attr({ id: $(this).attr("id") + " num_" + ++i });
})
});
A div element can only have one identifier and this identifier must be unique.
So you can't append an id.
An element in html have atmost single id. To solve this problem use customised attributes. Start using 'data-id' and use them as the normal html attributes. If you want to add more ids you just increment number. like...
input id='name' data-id='username'

How to properly do JS condition?

I run this jQuery (1.8.3) code and always get the "in" alerted even when the length is greater than 1.
What I'm doing is dynamically adding elements to a menu and the if is to make sure this element doesn't exist yet.
I tried also == 0 and === 0 but the result is the same...
Here is a JS fiddle: http://jsfiddle.net/mHhwq/4/
$(".sidebarit a.olink").click(function(event){
iframe_url = $(this).attr("href");
sidebar_id = '#' + iframe_url.replace(/[/.]/g, '');
alert('sidebar_id: ' + sidebar_id);
// create the sidebar if it doesn't exist
if ($(sidebar_id).length < 1) {
alert("in");
$("#sidebar_nav ul").append('<li></li>');
$("#sidebar_content").append('<div id="' + sidebar_id + '" style="display:none;"></div></div>');
} else { alert("out"); }
// don't follow the link
event.preventDefault();
});
In FireBug I see the length equals 1 but still enters the block.
What am I doing wrong?
Update:
My mistake was that I added the # at the wrong place...
Try to put alert inside if stmt as alert($(sidebar_id).length).
And you are making a mistake in appending the div to$("#sidebar_content").
Where sidebar_id is something like #test from sidebar_id = '#' + iframe_url.replace(/[/.]/g, ''); and you are appending like <div id= "#test" there, where it should be <div id= "test"(No # symbol is requird for id).
Your code will results like
$("#sidebar_content").append('<div id="#test" style="display:none;"></div></div>');
Change to
$("#sidebar_content").append('<div id="test" style="display:none;"></div></div>');
Then try again.
You must not have more than one element with the same ID. jQuery takes just the first in such a case.
To prove this have such HTML:
<div id="mydiv">hello</div>
<div id="mydiv">world</div>
Then this code:
var myDiv = $("#mydiv");
alert("length: " + myDiv.length + ", contents: " + myDiv.html());​
Test case.
If you have more than one element you need to iterate, use class instead or alternatively make sure to have unique ID for each sidebar and take the one closest to the clicked element.

Dynamically assign id to div and use that to call jquery slide effects

I am reading contents from JSON file and adding to div with unique IDs. I need to call jquery slide down effects to each div. Lets us consider the case, on clicking (div id=A1) it should slide down and show (div id=B1), in that way I have div with IDs A(1..N) and B(1..N).
var i=1;
$.each(items, function (index, item) {
$(document).ready(function(){
$("#A"+i).click(function(){
$("#B"+i).slideToggle();
});
});
$("#allContents").append('<div id="A'+i+'">' + item.Name + '</div>');
$("#allContents").append('<div id="B'+i+'">' + item.Details + '</div>');
i++;
});
This is the closest code I could derive to, but it is not working. If anyone could help me fix or suggest a better way to get this thing working it would be great. Thanks a lot!
$('#allContents').on('click', 'div[id^=A]', function() {
$('div#B' + this.id.replace('A','')).slideToggle();
});
A little explain
div[id^=A] point out those div whose id start with A.
this.id retrieve the id of clicked element.
this.id.replace('A','') replace A form the id and get the numeric index which equal to index of B.
$('div#B' + this.id.replace('A','')) point to element id=B1, id=B2 and so on.
Full code
// you can bind event handler outside ot loop
$('#allContents').on('click', 'div[id^=A]', function() {
$('div#B' + this.id.replace('A','')).slideToggle();
});
$.each(items, function(index, item) {
$("#allContents").append('<div id="A' + i + '">' + item.name + '</div>');
$("#allContents").append('<div id="B' + i + '">' + item.Details + '</div>');
i++;
});
Working Sample
Note
As you're creating div from A(1..N) and B(1..N) dynamically so you need delegate event handler (aka live event).
Syntax of jQuery .on() for delegate event is like following:
$(container).on(eventName, target, handlerFunction)

How to select for something that begins with a string but doesn't end with a different string in jQuery?

I am new to jQuery, exploring its syntax a bit.
My page has elements like this:
<area id="SA" ... />
<area id="AF" ... />
<area id="EU" ... />
<area id="NA" ... />
I am trying to show and hide div sections based on click events off the area tags, which have matching ending ID's, coded like this:
<div id="div_SA" ... />
<div id="div_AF" ... />
<div id="div_EU" ... />
<div id="div_NA" ... />
So, to show the exact match, but hide all the div sections which have id's that start with "div_" but don't otherwise match, without hiding every other div on the page, I tried this:
var q = 'div[id="div_' + event.target.id + '"]';
var r = 'div[id^="div_"],div:not[id$=' + event.target.id + '"]';
$(q).show();
$(r).hide();
$(r).hide(); is not working. What am I doing wrong? (I know I could assign CSS classes and get at them with class names, but I'm still curious about how to construct a query that will work this way.)
Make things as easy and simple as possible, since you are new at jQuery, you should get the habit of using on(). Not click(), that is outdated, and simply just refers to the on method.
$('area').on('click', function() {
var id = "#div_" + $(this).attr('id'), // comma allows you to make multiple variables
divs = $('div').hide() // puts all the divs in a variable and automatically hides them all
// filter through all the divs, and selects the one with the id,
// of the area that was clicked, and shows it
divs.filter(id).show();
});​
Hope this could help you for now. If not, please let me know.
Edit: See below for the syntax fix as mentioned in your post,
var q = '#div_' + this.id;
var r = 'div[id^="div_"]:not("#div_' + this.id + '")';
$(r).hide();
$(q).show();
DEMO
Please check the alternate solution below,
For evaluating q, I would simply use
var q = $('#div_' + this.id);
And for r,
var r = $('div[id^="div_"]').not(q);
r.hide();
q.show();
DEMO
The not css pseudo selector uses parenthesis not brackets. Also you have an unmatched quotation mark towards the end before the last bracket.
var r = 'div[id^="div_"],div:not(#' + event.target.id + ')';
Also, your code can be simplified by changing it to:
var q = '#' + event.target.id;
var r = 'div[id^="div_"]:not(#' + event.target.id + ')';
$(q).show();
$(r).hide();
How about this:
$('area').click(function() {
var areaID = $(this).attr('id');
$('div[id^="div_"]').hide();
$('div[id^="div_' + areaID + '"]').show();
});​
//start by selecing all of the DIV elements that have an ID attribute that starts with "div_",
//and hide all of them,
//then filter that list down to only the element(s) that have an ID that ends with the id of the `event.target` element
//and show that/those element(s)
$('div[id^="div_"]').hide().filter('#div_' + event.target.id).show();
Short and simple
// cache divs, no need to search them again
var divs=$('div[id^="div_"]');
$('area').click(function(){
divs.hide().eq( $(this).index() ).show();
});

Select appended item jquery

How would i select the below item, i do not want to select every LI of .top but just the LI i have just created on the append.
How is this possible?
$('.top').append('<li><span>' + html + '</span></li>');
You could do it the other way around using appendTo()
var li = $('<li><span>' + html + '</span></li>').appendTo('.top');
This way you don't have to select it after appending it.
Use the :last pseudo-class selector.
$('.top > li:last')
Alternate option: consider creating the element slightly differently.
var $li = $('<li><span>' + html + '</span></li>');
$('.top').append($li);
// you already have the <li> selected, in $li
You could probably select the last one:
$('.top').last()
See: http://api.jquery.com/last/

Categories