Get nested DIV's classes on click - javascript

Here's the HTML:
<div id="star" class="star1">
<div id="star" class="star2">
<div id="star" class="star3">
<div id="star" class="star4">
<div id="star" class="star5">
</div>
</div>
</div>
</div>
</div>
And the Javascript:
$(document).ready(function() {
$('#star').click(function(e){
e.stopPropagation();
var class_name = $(this).attr('class');
alert(class_name);
});
});
The problem I'm having is I'm only ever getting the class of the first parent div.
I want get the class from whichever div is being clicked on. Is there a way of doing this?

The ids of html element should be unique. Assign unique ids and use class selector and assign common class to group them.
Live Demo
<div id="star1" class="star">1
<div id="star2" class="star">2
<div id="star3" class="star">3
<div id="star4" class="star">4
<div id="star4" class="star">5
</div>
</div>
</div>
</div>
</div>​
$('.star').click(function(e){
e.stopPropagation();
var id = $(this).attr('id');
alert(id);
});
The approach you are using is not correct but some time you are bound to use such false patterns if it is so you can do it this way.
Live Demo
$('[id=star]').click(function(e){
e.stopPropagation();
var class_name = $(this).attr('class');
alert(class_name);
});​

Your code seems to be trying to find a unique identifier for each div. If that is what you are trying to do then you can switch the values of the class attribute with those of the id attribute.
HTML
<div id="star1" class="star">
</div>
JavaScript
$(document).ready(function() {
$('.star').click(function(e){
e.stopPropagation();
var id = $(this).attr('id');
alert(id);
});
});
In HTML the IDs of elements are meant to be unique whereas the class attribute can be used for multiple elements.

First of all bear this in mind, you do not use the same id for multiple tags.
<div id="star1" class="star">1
<div id="star2" class="star">2
<div id="star3" class="star">3
<div id="star4" class="star">4
<div id="star5" class="star">5
</div>
</div>
</div>
</div>
</div>
<script>
jQuery(function($){
$('.star').click(function(e) {
e.stopPropagation();
$('#out').html("My Class: "+$(this).attr('class')+ " My Id:" + $(this).attr('id'));
});​
});
Please check this fiddle , this might be something you are looking for

Related

JQuery - Add class on click verifying ID

I'm trying to add a class to a specific element that contains a parent container with a unique ID.
I have several buttons contained in a div, and all of them are using the same classes. For some reason, I can't use only $(this), so I created a loop that adds a unique ID to the containers.
HTML
<div class='section'>
<div class='btn-container' id='btn-1'>
<button class='btn'></button>
</div>
<div class='btn-container' id='btn-2'>
<button class='btn'></button>
</div>
<div class='btn-container' id='btn-3'>
<button class='btn'></button>
</div>
</div>
JQuery
$("button").click(function (e) {
e.preventDefault();
var target = $(e.target).parents(".button-container").attr("id");
console.log(target);
$(target).find(".btn").addClass("active");
});
I'm targeting the ID and it works, the console.log gives me back the correct info. However, for some reason, I can't add the class.
Thank you in advance for any help! (:
Edited:
I'm trying to add the class active to the button that is contained in the ID.
Example:
$("#btn-1 .btn").addClass("active"); but with the ID dynamically populate based on the info from the click.
Keep things simple, this should work
$(document).ready(function() {
$("button").click(function (e) {
e.preventDefault();
$(e.target).addClass("active")
});
});
.active{
border: 1px red solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='section'>
<div class='btn-container' id='btn-1'>
<button class='btn'>Test</button>
</div>
<div class='btn-container' id='btn-2'>
<button class='btn'>Test</button>
</div>
<div class='btn-container' id='btn-3'>
<button class='btn'>Test</button>
</div>
</div>

jQuery element removal

I want to remove an element using jQuery.
HTML:
<div class="listContainer" id="listContainer">
<div class="listItem">
<div class="name">
Item Name
</div>
<div class="amount">
<input type="text" class="amountInput" />
</div>
<div class="delete">
<div class="deleteBtn">
X
</div>
</div>
</div>
</div>
There are several listItemss on the page and each of the listItem will be created dynamically using jQuery. I want to delete amountInput of specific listItem by clicking the deleteBtn, so I tried doing:
$("#listContainer").on("click", ".deleteBtn", function() {
$(this).closest(".amountInput").remove();
});
This doesn't work. But on the other hand if I try to delete a listItem as a whole, the code works:
$("#listContainer").on("click", ".deleteBtn", function() {
$(this).closest(".listItem").remove();
});
Why is this happening?
Thanks.
Because .closest propagates to the top of the HTML. So it searches for the first parent that matches your selector. That is why it cannot find .amountInput. Because it isn't a parent of your button.
To get .amountInput you have to:
$("#listContainer").on("click", ".deleteBtn", function() {
$(this).closest(".listItem").find('.amountInput').remove();
});
This will get the wrapping .listItem element and then search it for the .amountInput element.
Your selector is not correct, use find instead of closest could be helpful in this case, also $(this) in your sample is related to deleteBtn class not to listContainer.
$("#listContainer").on("click", ".deleteBtn", function() {
console.log($(this)) // this here is .deleteBtn not listContainer
$(this).closest(".listItem").find(".amountInput").remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="listContainer" id="listContainer">
<div class="listItem">
<div class="name">
Item Name
</div>
<div class="amount">
<input type="text" class="amountInput" />
</div>
<div class="delete">
<div class="deleteBtn">
X
</div>
</div>
</div>
</div>

On click not working after appending checkbox elements in jquery

The contact_container div holds contact children, within these children is a checkbox. I use ajax to append these children to the container. Once I append the html and click a childs checkbox. The .click does not recognize the newly added checkboxes, Only the children work on page load. Below are working samples of my HTML and Jquery.
Can you offer a solution so that the appended checkboxes are picked up when they are clicked? Thanks
Here is my HTML markup:
<div id="contact_container">
<div class="contact">
<div class="contact_checkbox">
<div class="checkbox_container">
<div class="checkbox">
<input class="testing_checkbox" type="checkbox" name="contacts[]" value="bf6b0049059ec8998601f8fe20acb68ecafe2d44">
</div>
</div>
</div>
<div class="contact_info">
<div class="contact_image">
<img src="image.jpg" width="50" height="50" alt="Profile Picture">
</div>
<div class="contact_name"><span>Caroline Airey</span>
</div>
</div>
</div>
</div>
<div id="x_message" class="inputdata" style="overflow: hidden; display: none;">
<label>Message:</label>
<span><textarea name="x_message" placeholder="Enter a message to send to your contact(s)"></textarea></span>
<div class="clear"></div>
<button class="form_button">Add Contact to Network</button>
</div>
Here is my Jquery:
$( ".checkbox" ).click(function() {
var checked = $('.testing_checkbox:checked').length;
$('#testing').val(checked);
if (checked > 0){
$('#x_message').show(1000);
}
else{
$('#x_message').hide(1000);
}
});
You will need the Parent reference to bind the element properly to jquery try this
$(parentObj).on("click",".checkbox",function() {
var checked = $('.testing_checkbox:checked').length;
$('#testing').val(checked);
if (checked > 0){
$('#x_message').show(1000);
}
else{
$('#x_message').hide(1000);
}
});
The parentObj is the div or the html element you've appended the html code with ajax call
Use this jQuery method instead:
$(".checkbox").on("click", function()
{
// Your code here
});
This will grab clicks from elements that are dynamically added to your page after it initially loads :)

Onclick event issue after using the outerHTML

this is the code :
$(".adauga_incasare").click(function(){
var html = $(".incasari")[0].outerHTML;
$(html).insertAfter($(".incasari").last());
});
$(".del_incasare").click(function(){
alert("dsdasdasd");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<div class="incasari">
<div class="data_incasare_container">
<label><b>Data</b></label>
<input class ="data_incasare" type="text" id="datepicker">
<label class ="data_incasare_hidden">12-06-2014</label>
</div>
<div class="suma_incasare_container" style="">
<label><b>Suma</b></label>
<input class="suma_incasare" type="text" maxlength="8" name="pret_unitar[]" alt="">
<label class ="suma_incasare_hidden">100</label>
</div>
<div class="coscos" style="">
<a class="stergereIncasare" href="javascript:void(0);"><i class="icon-trash"></i></a>
<div style="clear:both;"></div>
<div class ="incasare_action">
<input class="btn btn-success" type="button" style="margin-left:50px;width:80px;height:30px;float:left;" value="Salveaza"></input>
</div>
<div style="clear:both;"></div>
</div>
<div style="clear:both;"></div>
</div>
<div style="clear:both;"></div>
+ Adauga incasare noua
<div class="toram">
<label style = 'cursor:default;'>Total incasat: <b>100 €</b></label>
<label style = 'cursor:default;'>Total ramas: <b>1012 €</b></label>
</div>
</div>
the outerHTML works fine, but when i "clone" the class incasari after that , when the onclick event doesnt work on the clone part. I have a delete button. In the first class "incasari" in works , but in the clone class it does not . Why ?
Use Event Delegation because your element is dynamically created after the click event was assigned. For example, to delegate to the document:
Demo
$(document).on("click", ".del_incasare", function(){
alert("dsdasdasd");
});
This means all clicks will be checked by the .del_incasare selector, and if it matches then the function will run, regardless of when the element was created.
The method you used to fire click event only works with the DOM elements that has been created during page load, DOM elements created dynamically would not be handled by this method.
For the elements created after page load or dynamically you have to use Event Delegation. For this use jQuery on method.
$(document).on("click", ".del_incasare", function(){
// do some cool stuff here.
});
You can use any parent element instead of document here, that was already in DOM during page load.

Change an ID value of a form element with javascript

I have a requirement to change the id of a form element dynamically. For example, the elements are in a sequence in form like id1, id2, id3 and id4 (the number of elements is not fixed to 4 and can be more than that). I need to add an element after id1 as id2. when this happens, the id2 which already in the form should change as id3 and id3 should change as id4 and so on. I thought of putting it in a recursive function with javascript but didn't get any idea as of now....Please help.
With jquery you can do this:
You have some html tags with class "listItem" and an id.
<div id="1" class="listItem">something </div>
<div id="2" class="listItem">something </div>
<div id="3" class="listItem">something </div>
Then the script
var i = 2;
$(".listItem").each(function() {
$(this).attr("id", i++);
});
This should change the content to
<div id="2" class="listItem">something </div>
<div id="3" class="listItem">something </div>
<div id="4" class="listItem">something </div>
This will iterate through all tags that have class "listItem" and will change the id.
I hope that helps.
Lets say your html was like this:
<div id="id1" class="list"></div>
<div id="id2" class="list"></div>
<div id="id3" class="list"></div>
You can create a function that inserts a new element in the middle and updates the ids of all the following elements in two steps as follows:
function(insertAfterId) {
jQuery('#' + insertAfterId).insert('<div id="temp" class="list"></div>');
var count = 1;
jQuery('.list').each(function() {
jQuery(this).attr("id", "id" + count);
count++;
});
}
Hope that helps!

Categories