Run javascript function for dynamically inserted HTML - javascript

I have a piece of code that on hover of another element insert's this code below.
<div class="star" id="1">
<div class="star" id="2">
<div class="star" id="3">
<div class="star" id="4">
<div class="star" id="5">
</div>
</div>
</div>
</div>
</div>
All I want to do is retrieve the ID of each DIV through javascript:
$(document).ready(function() {
$('.star').on(function(e){
e.stopPropagation();
var rating = $(this).attr('id');
alert(rating);
});
});
I've tried many ways of achieving this, this is the latest I've tried but I'm still having no luck! I'll be grateful of any help

Trigger an event when said divs are added.
var counter = 0;
$(someelement).on("mouseenter",function(){
counter++;
$('<div class="star" id="' + counter + '" />').appendTo(".star:last").trigger("staradded");
})
$(document).on("staradded",".star",function(e) {
alert(this.id);
});
Or better yet, skip the event.
var counter = 0;
$(someelement).on("mouseenter",function(){
counter++;
$('<div class="star" id="' + counter + '" />').appendTo(".star:last");
alert(counter);
})

I would use "livequery" plugin - https://github.com/brandonaaron/livequery
If I understood correctly, you need something like old function "live", since you would like to watch all new ".star" elements.
In this case you will just use following code:
$('.star').livequery('click',function(e){});
Simple example you can find there - http://jsfiddle.net/WEr5J/11/

You have wrong syntax of on as you are not telling what event you want to bind. After binding your required event e.g. click you can use map function to get all the comma separated ids of elements having class star.
Live Demo
$(document).on('click', '.star', function(e) {
e.stopPropagation();
ids = $('.star').map(function() {
return this.id;
}).get().join();
alert(ids);
});
You need to use each to iterate through all elements.
$('.star').each(function(){
var rating = $(this).attr('id');
alert(rating);
});
​

Related

Jquery clicking dynamic created elements with buttons and on doesn't work

I know there are a lot of answered questions here, but I think this is a more specific problem.
I populate a div with dynamically generated products. Each product has an input field with a plus and min button to adjust the amount inside the input.
Whatever I try I can't get it to work. I know I have to use on to click dynamic elements.
My HTML
<div class="carousel-wrapper">
<div class="custom-products" data-getnew="popular-products"></div>
</div>
<div class="carousel-wrapper">
<div class="custom-products" data-getnew="newest-products"></div>
</div>
My Jquery
function customProducts(url, container){
$.get(url + '?format=json', function(e){
var productsHtml = [];
$.each(e.products, function(index, product) {
var productHtml = '<div class="col col-25 m-50 t-25 item-grid"><div class="item quick-view-item clearfix" data-handle="'+product.url+'" data-vid="'+product.vid+'">
.......
.......
productHtml = productHtml + '<div class="to-cart"><form action="/cart/add/'+product.vid+'" id="product_configure_form_'+product.id+'" method="post"><div class="custom-quantity-input"><input type="text" name="quantity" value="1"><div class="item-quantity-btns"><div class="up quantity-btn quantity-input-up"><i class="fa fa-plus"></i></div><div class="down quantity-btn quantity-input-down"><i class="fa fa-minus"></i></div></div></div><button type="submit" class="item-add-btn-cart btn btn-custom-1 with-qty redirect" title=""></button></form></div> </div> </div> </div> </div>';
productsHtml.push(productHtml);
});
productsHtml = productsHtml.join('');
$(container).html(productsHtml);
})
}
And then run it like this:
$(function(){
$('.carousel-wrapper .custom-products').each(function(){
var url = $(this).data('getnew')
var container = $(this)
customProducts(url, container)
});
To click the plus/min buttons
$('.carousel-wrapper .custom-products').each(function(){
$('.item-grid').on('click', '.up', function (){
console.log($(this))
alert('test')
});
$('.item-grid').on('click', '.down', function (){
console.log($(this))
alert('test')
});
});
.....
Why does this not work? Console and alert don't show anything. To my understanding you have a static container with the dynamic items and then you select the button with .on. What's wrong with that?
Any help greatly appreciated.
You have to trigger the event on the document when elements are created dinammically.
$(document).on('.item-grid .down', 'click', function (){

click a div and get the id of another div

I want to click on a element and get the id from another div which is not related to it.
I tried this:
$(".map_flag").on("click",function(){
var objective = ($(this).attr("data_modal"));
$("#" + objective).fadeIn(300, function(){
$("#" + objective).find(".modal_content").fadeIn(300);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="map_flag" data_modal="map_1">
<img src="img/image_1.png" alt="image one" >
</button>
<div id="map_1">
<p class="modal_content">place holder</p>
</div>
First of all, custom attributes need to start off with data- not with data_ (note the dash/underscore).
Then
$("#" + objective).fadeIn(300, function(){
$("#" + objective).find(".modal_content").fadeIn(300);
});
first fades in $('#map_1') and then, after that's been done, fades in $('#map_1 .modal'). Not sure if that's intended, but if the #map_1 elements has no further children, you might want to fade in only once.
For the rest, your code should work fine.
I think what you need would be something like this:
<button class="map_flag" data-modal="map_1">
<img src="img/image_1.png" alt="image one" >
</button>
<div id="map_1">
<p class="modal_content">place holder</p>
</div>
And then in JavaScript
$(".map_flag").on("click",function(){
// You should use data-* attributs as jQuery has a special function
// .data("name") that obtains the value of property data-name for example
var objective = $(this).data("modal");
$("#" + objective).fadeIn(300, function(){
$("#" + objective).find(".modal_content").fadeIn(300);
});
});
I am not very confident about my jquery skills, but dont you need to "fade out" before fade In ?
[https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_eff_fadeout_fadein]

Dynamically added semanctic ui checkbox / radio / rating events not firing

Dynamically added checkbox / radio buttons / rating elements are not firing the attached events in semantic ui. Below is the js fiddle for sample and its not all triggering the events when check box is checked i have tried both 'setting' option and onChange separately as well. nothing is working as expected.
Javascript :
$("#cbdiv").checkbox('setting', 'onChange', function() {
alert("Changed");
});
$("#addcheckboxes").unbind();
var chkcounter = 0;
$("#addcheckboxes").bind('click', function() {
$('#chkgrp').append("<div id='chkbx_'" + chkcounter + "class='ui checkbox'><input type='checkbox' ></div>");
$('#chkbx_' + chkcounter).checkbox({
onChange: function() {
alert('i am added. my id is : ' + $(this).attr('id'));
}
});
});
Html
<div class="field">
<div id="cbdiv" class="ui toggle checkbox">
<input type="checkbox" id="confirm" name="confirmed">
<label>Confirmed</label>
</div>
<div>
<button id="addcheckboxes">Add checkboxes</button>
<div id="chkgrp">
</div>
</div>
</div>
Jsfiddle sample
It is because of the append statement adding wrong id element. After the append statement execute, if you look at your html it will look like below.
<div id="chkgrp">
<div id="chkbx_" 0class="ui checkbox">
<input type="checkbox">
</div>
</div>
After the above code execute, you are searching for the id chkbx_0 through jquery and try to add the onChange event for that. So it is failed. Update your append element syntax like below and it will work.
$('#chkgrp').append("<div id='chkbx_" + chkcounter + "' class='ui checkbox'><input type='checkbox' ></div>");
In the above code, I have closed id string after adding chkcounter id='chkbx_" + chkcounter + "'. In your earlier code you have closed the id string before adding the chkcounter itself id='chkbx_'" + chkcounter + ".
UPDATE
Looks like your semantic css have the following styles.
.ui.checkbox input {
position: absolute;
top: 0px;
left: 0px;
opacity: 0;
outline: 0px;
}
Because of the above styles you are not able to see the checkboxs. If you want to see the styled checkbox then you have add the label to your check box and update your code like below.
$('#chkgrp').append("<div id='chkbx_" + chkcounter + "' class='ui checkbox'><input type='checkbox'><label>test</label></div>");
Also I have noticed that you are trying to get the ID of the element using $(this).attr('id'). This statement will give the output undefined, because the checkbox does not have any attribute called id. I hope you are trying to get the id chkbx_0. In that case you have to add your code like below.
$(this).parent().attr('id');
I have updated your fiddle with all the above changes and you can see the demo here.
In checkbox code ID name is not set properly that's is the reason. You can see below working code
$("#addcheckboxes").bind('click', function() {
chkcounter++; // set counter increment
$('#chkgrp').append("<div id='chkbx_"+chkcounter+"' class='ui checkbox'><input type='checkbox' name='checkboxval[]' id='checkbox_id_"+chkcounter+"' ></div>");
$('#chkbx_'+chkcounter).checkbox({onChange:function(){alert('i am added. my id is : '+$(this).attr('id'));}});
});
Hope this will help you.

Jquery dynamic creating HTML divs on click

I’m looking for some direction for my problem.
I’ve HTML divs and I want to replicate it when user clicks on span with id plus-1.
This is my html
<div id = “tab”>
<div class="row">
<div>
<select id="ProjectsFolder0FolderId" name="data[ProjectsFolder][0][folder_id]">
<option value="1">Project Presentation</option>
<option selected="selected" value="4">Project Root</option>
</select>
</div>
<div>
<div>
<input type="text" required="required" id="ProjectsFolder0Linux" value="xyz" name="data[ProjectsFolder][0][linux]">
</div>
</div>
<div id="plus-1" >
<span>
Click here
</span>
</div>
</div>
</div>
Jquery
$(document).on('click', '#plus-1' , function() {
var html = "<div class=\"row\" >"
???
+ "</div>";
$('#tab').append(html);
});
It is appending above html defined in jquery , but I don’t know how to append entire HTML efficiently as required above on each click.
Demo FIDDLE
Jquery
$(document).on('click', '#plus-1' , function() {
var html = $(this).parent().clone();
html.find('#plus-1').attr('id','plus-'+($('#tab').find('.row').length+1));
$('#tab').append(html);
});
Made a jsfiddle for you - http://jsfiddle.net/23GCn/. You also have an error in your html, you need to use correct parenthesis on <div id="tab">
jQuery(function($){
var count = 1;
$(document).on("click", "[id^='plus']", function(){
newBlock = $(this).parents(".row").clone();
count += 1;
// change id of Plus button
newBlock.find("[id^='plus']").attr("id", "plus-"+count);
// Change id and name of select box
newBlock.find("select")
.attr("id", "ProjectsFolder"+count+"FolderId")
.attr("name", "data[ProjectsFolder]["+count+"][folder_id]");
// Same for input
newBlock.find("input[type='text']")
.attr("id", "ProjectsFolder"+count+"Linux")
.attr("name", "data[ProjectsFolder]["+count+"][linux]");
// append new element to your tab
$("#tab").append(newBlock);
});
});
Note that [id^='plus'] type selectors are very inefficient, means, slow. Consider using classes instead of ids, this way you avoid all of the code required to change ids, since you can't have elements with same id on your page obviously.

How to get the child of an element using an event trigger and a custom attribute?

I hope you can help me with my problem.
Here's my sample code
<input type="checkbox" data-attr="getAllChoices" />
<div id="parent">
<div id="child1">
<input type="checkbox" value="3"/>Choice A
</div>
<div id="child2">
<input type="checkbox" value="5"/>Choice B
</div>
<div id="child3">
<input type="checkbox" value="6"/>Choice C
</div>
</div>
Scenario:
If if the user check the checkbox, all choices should be check also. The date-attr should be use for comparing. If it has a value it will call the child of the parent (checkboxes) and check it all.
So far in my js I have this. But I don't have an idea how to call the other checkboxes.The only thing that I know is call the checkboxes by accessing the child div.
$("input[data-attr='checkAll']").on('change',function(){
//no idea. . . . .
});
By the way I am using jquery 1.5
I don't see the data-check attribute. So try using the data-attr attribute:
$("input[data-attr='getAllChoices']").bind('change',function(){
$('#parent').find('input[type=checkbox]').attr('checked', this.checked);
});
If you want to avoid the use of attr() for the checked property, you can iterate over the checkboxes manually:
$("input[data-attr='getAllChoices']").bind('change',function(){
var isChecked = this.checked;
$('#parent').find('input[type=checkbox]').each(function(i, val){
val.checked = isChecked;
});
});
Try this :
$("input[data-attr='getAllChoices']").bind('change', function () {
$('#parent input[type="checkbox"]').attr('checked', this.checked)
});
Try this, uses change method in jQuery 1.5:
$(document).ready(function () {
$('input[data-attr="checkAll"]').change(function () {
$('#parent').find('input[type=checkbox]').attr('checked', this.checked);
//OR
// $('#parent input[type=checkbox]').attr('checked', this.checked);
});
});
Here is the Demo

Categories

Resources