I couldn't pick a specific li element on click which is generated dynamically. please help.
Jquery
$(document).ready(function()
{
$('#id1').on('click', 'li', function(e)
{
var val = $(this).find('.pick').attr('data-val1');
console.log(val); // returns only first value for every click
});
});
Dynamically created HTML
var x = document.getElementById("id1");
x.innerHTML= x.innerHTML + '<li class="pick" data-val1="'+i+'"></li>' // where i is a incremental counter
HTML
<ul id ="id1">
// li adds here
</ul>
Try this solution: http://jsfiddle.net/nec47v8d/
You can use this JQUERY
$('#id1 li.pick').click(function (e) {
var val = $(this).attr('data-val1');
alert(val)
});
Try
$(document).ready(function() {
$('#id1').on('click', 'li', function(e) {
var val = $(this).attr('data-val1');
snippet.log('clciekd: ' + val); // returns only first value for every click
});
var i = 0;
$('button').click(function() {
$('<li />', {
'data-val1': ++i,
text: i
}).appendTo('#id1');
})
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="id1"></ul>
<button>Add</button>
Related
What is the best way to detect if a jQuery-selector clicked. i mean:
var elem = 'foo'
var action = $(elem ).mouseenter(function(){
$(this).css('background-image',url(elem +'.png'))
});
var elem = 'bar'
//do the same action with new elem
var elem = 'blah'
//do the same action with new elem
the problem is how can i shorten this code to one line:
$('.far').mouseenter(function(){$(this).css('background-image',url(far.png'))});
$('.foooo').mouseenter(function(){$(this).css('background-image',url(foooo.png'))});
$('.bar').mouseenter(function(){$(this).css('background-image',url(bar.png'))});
$('.some').mouseenter(function(){$(this).css('background-image',url(some.png'))});
try making this array
var arr = [ "far", "foooo", "bar", "some" ];
arr.forEach( function( item ){
$('.' + item ).mouseenter(function(){$(this).css('background-image','url('+ item +'.png'))});
//adding the click detection as well
$('.' + item ).click(function(){$(this).css('background-image','url('+ item +'.png'))});
});
$(function() {
$(document).on('mouseenter', 'div[data-background]', function() {
$(this).css({'background' : 'url('+$(this).data('background')+')',});
});
});
div {
width : 500px;
height : 320px;
border : 1px solid #A2A2A2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head></head>
<body>
<div data-background="https://cdn.pixabay.com/photo/2017/04/04/14/23/peacock-2201428_960_720.jpg"></div>
<div data-background="https://cdn.pixabay.com/photo/2013/07/12/18/59/peacock-154128_960_720.png"></div>
</body>
</html>
Works only in this situation.
Since you have single class selector,assuming you don't have multiple classes
$('.far','.foooo','.bar','.some').mouseenter(function(){
var selector = $(this).attr('class');
$(this).css('background-image',url(selector+'.png'));
});
You need something like this:
$(".foo").click(function (event) {
$(this).css("color", "red");
});
Again, you need click, not mouseenter. Because mouseenter is just a hover, which you could do with plain css.
For some reason I'm having a hard time implementing draggable (either jquery's or draggabilly) on JSON/jquery-created elements.
This is my jQuery along with the JSON.
var setTotal = function (){
var total = 0;
$('.block').each(function(){
total = total+parseInt($(this).data('cost'));
});
$('.totalSum').html(total);
};
window.onload = function(){
$.getJSON( "ajax/test.json", function( data ) {
$.each( data.createButton, function( key, val ) {
var button = $('<button class="btn" id="' + val.name +'" style="background: ' + val.color + '">' + val.name + '</button>');
button.on("click", function(){
//console.log("button " + val.name + " was clicked!");
var block = $('<div id="draggable" class="block ' + val.name + '-piece">'+ val.name + '<div class="close">-</div></div>');
block.data('cost', val.cost);
block.on("click", ".close", function(){
$(this).parent().remove();
// call set total to refresh it when item is removed
setTotal();
});
$('#boxes').append(block);
// call set total to calculate total blocks' cost
setTotal();
});
$('#field').append(button);
});
});
};
and this is how it's called in the html document;
<!-- Grab Google CDN's jQuery -->
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<!-- Grab draggable -->
<script src="//cdnjs.cloudflare.com/ajax/libs/draggabilly/1.2.0/draggabilly.pkgd.min.js"></script>
<!-- My own scripts -->
<script src="js/main.js" type="text/javascript"></script>
<script>
var $draggable = $('#draggable').draggabilly({
// options...
});
</script>
<!-- End scripts -->
Now for some reason I can't target the ID (for testing only) nor the class (block) of the block variable. Does anyone know why? The draggable works fine with any other element on the page.
Sincerely, Sebastian
Two things :
you are appending multiple elements with id="draggable". Ids should be unique.
there's no evidence of invoking draggabilly on the appended elements.
Draggabilly needs to be invoked on :
any blocks that already exist on page load
dynamically created blocks after they have been appended
Personally, I would write the code something like this :
window.onload = function() {
var draggabilly_options = {
// options...
};
function create_button(key, val) {
$('<button/>', {
'id': val.name,
'class': 'btn',
'style': 'background-color:' + val.color,
'html': val.name,
})
.appendTo("#field")
.on('click', create_block.bind(val));
}
function create_block() {
$('<div/>' {
'class': 'block ' + this.name + '-piece',
'html': this.name + '<div class="close">-</div>'
})
.appendTo('#boxes')
.draggabilly(draggabilly_options) //invoke draggabilly on the div.block just added
.data('cost', this.cost)
.find('.close')
.on('click', close);
}
function close() {
$(this).closest(".block").remove();
setTotal();
}
function setTotal() {
var total = 0;
$(".block").each(function() {
total += parseInt($(this).data('cost'));
});
$('.totalSum').html(total);
};
$.getJSON( "ajax/test.json", function(data) {
$.each(data.createButton, create_button);
setTotal();
});
//You need this only if the page loads with any "draggable" blocks already in place.
$("#boxes .block").draggabilly(draggabilly_options);
};
Thank you for all responses. I took some advice from your code you published and put it like this;
// Start this after window is loaded
window.onload = function(){
// Init draggabilly
var draggabilly_options = {
// Dragabilly options
containment: '#boxes',
grid: [ 100, 100 ]
};
and also defined it further down in the button click function like so;
button.on("click", function(){
var block = $('<div id="block-' + val.id + '" class="block ' + val.name + '-piece"></div>');
var close = $('<div class="close">-</div>');
$(block).append(close);
block.data('cost', val.cost);
block.draggabilly(draggabilly_options);
This appeared to solve it for me! Thank you for the help and answers, they solved my problem :)
HTML:
<nav id="sales-countries">
<ul>
<li>...1...</li>
<li>...2...</li>
<li>...3...</li>
<li>...4...</li>
<li>...5...</li>
<li>...6...</li>
<li>...7...</li>
</ul>
</nav>
<nav class="sales-location">...1...</nav>
<nav class="sales-location">...2...</nav>
<nav class="sales-location">...3...</nav>
<nav class="sales-location">...4...</nav>
<nav class="sales-location">...5...</nav>
<nav class="sales-location">...6...</nav>
<nav class="sales-location">...7...</nav>
Javascript:
$("nav.sales-location").hide();
$("#sales-countries a:eq(0)").click(function() {
$("nav.sales-location").hide();
$("nav.sales-location:eq(0)").show();
});
$("#sales-countries a:eq(1)").click(function() {
$("nav.sales-location").hide();
$("nav.sales-location:eq(1)").show();
});
$("#sales-countries a:eq(2)").click(function() {
$("nav.sales-location").hide();
$("nav.sales-location:eq(2)").show();
});
$("#sales-countries a:eq(3)").click(function() {
$("nav.sales-location").hide();
$("nav.sales-location:eq(3)").show();
});
$("#sales-countries a:eq(4)").click(function() {
$("nav.sales-location").hide();
$("nav.sales-location:eq(4)").show();
});
$("#sales-countries a:eq(5)").click(function() {
$("nav.sales-location").hide();
$("nav.sales-location:eq(5)").show();
});
$("#sales-countries a:eq(6)").click(function() {
$("nav.sales-location").hide();
$("nav.sales-location:eq(6)").show();
});
I need, that element of specific number - button, show an element of specific number.
JavaScript code above have this property and work well, but it is too long.
How I make this property for (for example) one hundred buttons and elements for showing so that JavaScript code was very short?
Between code paragraphs is different in the two numbers only!
You can do it by a common function for every li click and you can show corresponding div by jquery index()
try this:
$("nav.sales-location").hide();
$("#sales-countries ul li").click(function() {
ind = $(this).index();//get the li index
$("nav.sales-location").hide();// hide all divs
$("nav.sales-location:eq("+ind+")").show(); //show corresponding index div
});
live demo
Reduce it to just:
$("nav.sales-location").hide();
$("#sales-countries a").click(function() {
$("nav.sales-location").hide();
$("nav.sales-location:eq("+$(this).index('#sales-countries a')+")").show();
});
jsFiddle example
You can pass a selector to .index() to specify what collection it's relative to.
since you're just showing the same text as the a that's clicked you can grab the value using .text() and pass it to an empty div called .sales-location
$("#sales-countries a").click(function() {
var results = $(this).text();
$(".sales-location").html(results);
});
JSFIDDLE
Try this:
var $locations = $("nav.sales-location").hide();
$("#sales-countries a").click(function () {
$locations.hide().filter(":eq(" + $(this).parent().index() + ")").show();
});
Demo: http://jsfiddle.net/bZLqR/1/
I did something like this kind of recently. This will do it even with Jquery.
var array = [ 1,2,3,4,5 ]
var list = document.getElementById('some-id');
function links(){ // generate links
for (var i in array){
var val = array[i];
var li = document.createELement('li');
li.innerHTML = "<a href='#'>" + val + "</a>"
li.onclick = show;
li.index = i; // save the array index for later
list.appendChild(li);
}
}
function show(e){
var index = e.target.index || -1 ;
var toShow = document.getElementsByClassName('class-name');
// hide all
for (var i in toShow){
toShow[i].style.visibility = 'hidden';
}
// show the one I want.
if (toShow.length < index && index >= 0){
toShow[index].style.visibility = 'visible';
}
}
links(); // build the links.
I want add a class when a <li> element clicked. but it didn't work. Here's JQuery snippet
$(".mama").click(function(){
var arr = ["cat","dog", "mice", "bird"];
alink = $(this).text();
$.each(arr, function(index, value) {
if(alink == value){
$(this).addClass('hi');
}
});
});
And HTML
<ul id="animal">
<li class="mama">cat</li>
<li class="mama">dog</li>
<li class="mama">Mice</li>
</ul>
i also have tried to do it by .map but nothing happen. please give solution and some explain. Thanks
This should work:
$(".mama").click(function(){
var $this = $(this);
var arr = ["cat","dog", "mice", "bird"];
alink = $(this).text();
$.each(arr, function(index, value) {
if(alink == value){
$this.addClass('hi');
}
});
});
because this inside the each is not the DOM element <li>.
You probably just need to do this:
http://jsfiddle.net/reugB/1/
$('.mama').on('click', function(evt) {
evt.preventDefault();
$(this).addClass('hi');
});
Use this to refer to current element which was clicked.
$(".mama").click(function (e) {
e.preventDefault();
$(this).addClass('hi');
});
If you mean add the class hi to the clicked li, just do like below:
$(".mama").click(function(e){
e.preventDefault();
$(".mama").removeClass('hi');
$(this).addClass('hi')
});
.hi { background-color: #f00 !important;}
$('.mama').on('click', function(evt) {
evt.preventDefault();
$(this).addClass('hi');
});
$(".mama").click(function(e){
e.preventDefault();
var arr = ["cat","dog", "mice", "bird"];
var alink = $(this).find("a").text();
$.each(arr, function(index, value) {
if(alink == value){
$(this).addClass('hi');
}
});
});
see reference text and find
I want to append a checkbox with each children.
For that I used
var len = $("#personalDetails").children("div").length;
for(var id=0; id<len;id++)
{
var el = $('<input type="checkbox"/>');
$("#personalDetails").children(":first").attr("id",id);
alert(id);
$( "#"+id).append(el);
}
html
<div id="personalDetails">
<div>personal</div>
<div>Education</div>
</div>
By doing this I got a problem. All checkboxes are coming under one div. How can I set one for one div and other for other div?
[Note: We can not put any id or class for children div]
http://jsfiddle.net/QTzrB/
you can
$(document).ready(function(){
$('#personalDetails > div').each(function(idx, el){
$('<input type="checkbox"/>').attr("id", idx).appendTo(el);
})
$('#personalDetails').on('click', 'input[type="checkbox"]', function(){
alert(this.id);
});
});
Demo: Fiddle
Try This
$(document).ready(function(){
var len = $("#personalDetails").children("div").length;
$("#personalDetails div").each(function(idx) {
$(this).append("<input type='checkbox' id="+ idx +" />");
});
$("input[type=checkbox]" ).on("click",function(){
alert($(this).attr("id"));
});
});
Fiddle Demo
You should cache the div list. Also if you don't want to put ids to the input elements then you can cache them also.
Below code is working on Fiddle.
$(document).ready(function(){
var divs = $("#personalDetails").children("div");
var len = divs.length;
for(var id = 0; id < len; id++) {
var el = $('<input type="checkbox"/>');
divs.eq(id).append(el);
}
});
replace your script with this one,hope this will do what you want.
$(document).ready(function(){
$('#personalDetails').children('div').each(function(){
$(this).append('<input type="checkbox"/>');
});
});
fiddle
$(document).ready(function(){
$("#personalDetails").children("div").each(function(index, obj) {
var $chk = $("<input/>",{"type":"checkbox"});
$(this).prepend($chk.attr("id",index));
$chk.on("click",function(){
alert(this.id);
});
});
});
Working demo here:
http://jsfiddle.net/HNezs/