Appending ID without replacing original - javascript

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'

Related

Jquery dynamically selector

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");

Making part of an Id name into a variable

I have a bunch of divs with matching ids (#idA_1 and #idB_1, #idA_2 and #idB_2, etc). In jquery I wanted to assign click functions, so that when I click an #idA it will show and hide an #idB.
Basically I want to make this:
$(".idA_x").click(function(){
$("idB_x").toggleClass("hide")
});
X would be a variable to make #idA and #idB match. I could write each individually, but that would take too much code, is there a way to make the number in the id into a variable?
Sure, you can do:
var num = 13;
addButtonListener(num);
function addButtonListener(num){
$("#idA_"+num).click(function(){
$("#idB_"+num).toggleClass("hide")
});
}
Try JQuery solution :
var x = 1;
$(".idA_" + x ).click(function(){
$(".idB_" + x ).toggleClass("hide")
});
Hope this helps.
There are many ways to achieve that, but what you probably want is to create a shared CSS class, e.g. .ids, and bind the event listener to that one:
$('.ids').click(function () {
//...
});
Then you can handle your logic in a cleaner way within the function body.
In order to make it dynamic, and not have to repeat the code for each one of your numbers, I suggest doing as follows:
First, add a class to all the div's you want to be clickable .clickable, and then use the id of the clicked event, replacing A with B in order to select the element you what to toggle the class:
$(".clickable").click(function(){
var id = $(this).attr('id');
$("#" + id.replace('A', 'B')).toggleClass("hide");
});
Or, you can also select all divs and use the contains wildcard:
$("div[id*='idA_']").click(function(){
var id = $(this).attr('id');
$("#" + id.replace('A', 'B')).toggleClass("hide");
});
This solution won't have the need to add a class to all clickable divs.
You can use attribute selector begins with to target the id's you want that have corresponding elements.
https://api.jquery.com/attribute-starts-with-selector/
Then get the value after the understore using split on the id and applying Array.pop() to remove the 1st part of the array.
http://jsfiddle.net/up9h0903/
$("[id^='idA_']").click(function () {
var num = this.id.split("_").pop();
$("#idB_" + num).toggleClass("hide")
});
Using regex would be your other option to strip the number from the id.
http://jsfiddle.net/up9h0903/1/
$("[id^='idA_']").click(function () {
var num = this.id.match(/\d+/g);
$("#idB_" + num).toggleClass("hide")
});

Adding selectors into dynamically generated <li > element

I am trying to dynamically generate html content. However it seem like whenever I add tags or selectors to the li element, the code malfunctions
Correct behavior
Incorrect behavior
$('#btnName').click(function(){
var text = $('#inputName').val() + '<button>x</button>';
if(text.length){
$('<li name="somename" id="someid"/>', {html: text}).appendTo('ul.justList') // adding name tag and id selector cause error
}
});
$('ul').on('click','button' , function(el){
$(this).parent().remove()
});
Demo
Use the second parameter to set the other attributes rather than write them out in the tag. Also, you don't need to self-close the tag.
$('#btnName').click(function(){
var text = $('#inputName').val() + '<button>x</button>';
if(text.length){
$('<li>', {
html: text,
name: 'somename',
id: 'someid' + $('.justList li').length // for the sake of unique ids in the example
}).appendTo('ul.justList')
}
});

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();
});

jQuery: get content / innerhtml onclick

If you click on a cell on this page, it loads the larger version of the image. I'm trying to achieve this same effect.
What I have gotten so far: http://jsfiddle.net/8mYW9/
First off I know having the "appear" <div> is redundant - is there a good way to utilize $(this) and appendTo(); instead?
Ultimately my idea is to grab the id of the anchor contained within the div that is clicked and to append it to the cell. What should I be doing...?
If you change the ID attribute to class for the appear elements you can do this:
$(document).ready(function() {
$('#appear').hide();
$('.links').click(function() {
var $this = $(this);//cache the $(this) selector since it will be used more than once
$this.children('.appear').html('item id: ' + $this.children('a').attr('id')).fadeToggle('slow');
});
});
Demo: http://jsfiddle.net/8mYW9/7/
BTW you can't have multiple elements with the same ID in a HTML document.
You could do that with:
$(document).ready(function() {
$('#appear').hide();
$('.links').click(function() {
$(this).append('<div>' + $(this).find('a:first').attr('id') + '</div>');
});
});
JS Fiddle demo.
Amended so that only one id is shown (others are removed before showing the latest):
$(document).ready(function() {
$('#appear').hide();
$('.links').click(function() {
$(this).closest('.container').find('.appended').remove();
$(this).append('<div class="appended">' + $(this).find('a:first').attr('id') + '</div>');
});
});
JS Fiddle demo.
Incidentally, it escaped my notice the first time, but with multiple elements sharing the same id you have invalid (X)HTML: an id must be unique within the document (citation: W3.org).
References:
attr().
closest().
find().
:first selector.
remove().
Try using class selectors instead. You've got duplicate IDs:
$(document).ready(function() {
$('.appear').hide();
$('.links').click(function() {
$(this).find(".appear").fadeToggle('slow', function() {
$(this).html('item id:')
});
});
});
http://jsfiddle.net/8mYW9/

Categories