I am loading dynamically divs that have a some class. At the end, I would like to multiple of the values from all of the class.
there is a code
$(document).ready(function(){
$('.show-tip').click(function(e) {
$(this.parentElement.parentElement.querySelector(".tip-kurz")).appendTo( "#betbuilder" );
var multiple = 0;
$('#betbuilder .tip-kurz').each(function()
{
multiple += Number($(this).text());
});
document.querySelector(".course").innerHTML = multiple;
});
i tried everything, but nothing works
Related
This is a follow-up to my previous question: Multiple checkbox filter: how to get both and additive and subtractive effect
Many thanks to everyone who helped me in my previous question. Basically, I want to make checkboxes that hide and show div items based on what class(es) they have. The filters are separated into two categories, with two options within each category: citiesFilter (hamiltonFilter + torontoFilter) and costFilter (cheapEatsFilter + costFilter).
Checking two boxes within each category should increase the number of <div> elements that appear (i.e. clicking 'hamiltonFilter' and 'torontoFilter' should show <div> elements that have either class)
Checking two boxes between two categories should narrow the number of <div> elements that appear (i.e. clicking 'hamiltonFilter' and 'cheapEatsFilter' should ONLY show <div> elements that have BOTH classes)
The previous answers work, but only within each category; it doesn't narrow the results when I click 'hamiltonFilter' and 'cheapEatsFilter', rather it shows me all <div> elements with either class. I tried modifying their code but cannot figure out how to select for <div> elements with both classes.
https://jsfiddle.net/de1zc7vx/1/
edit: put in the wrong jfiddle
$(document).ready(function() {
$('#checkboxFilterContainer').find('input:checkbox').on("change", function() {
var $citiesIDs, $costIDs = [];
var $citiesCategory = $('#citiesFilterContainer').find('input:checked');
var $costCategory = $('#costFilterContainer').find('input:checked');
$citiesCategory.each(function(index, element) {
$citiesIDs.push(element.getAttribute('id'));
});
$costCategory.each(function(index, element) {
$costIDs.push(element.getAttribute('id'));
});
var $totalLength = ($citiesIDs.length + $costIDs.length);
if ($totalLength == 0) {
$('.blogpost').removeClass('hide');
} else {
$('.blogpost').addClass('hide');
for(i = 0; i < $totalLength; i++) {
var x = $citiesIDs[i];
var y = $costIDs[i];
var xClass = $('.' + x);
var yClass = $('.' + y);
$('.x.y').removeClass('hide');
}
}
})
})
Add the hide class to all the posts
Make an OR selector for the selected cities (.firstId,.secondId,...)
Make an OR selector for the selected costs
If city ids were given, filter the posts by that OR selector
If cost ids were given, filter further (or for the first time) by that OR selector
For all the posts remaining, remove the hide class
var $filteredPosts = $('.blogpost').addClass('hide');
if ($totalLength) {
var citiesOrSelector = '.'+ $citiesIDs.join(',.');
var costsOrSelector = '.'+ $costIDs.join(',.');
if ($citiesIDs.length) $filteredPosts = $filteredPosts.filter(citiesOrSelector);
if ($costIDs.length) $filteredPosts = $filteredPosts.filter(costsOrSelector);
}
$filteredPosts.removeClass('hide');
Trying to add an incrementing class name to an element (rows in an ajax cart), while doing the same to one of it's child elements (images within each cart row).
After the items are numbered, show the matching image that has the same number in class name.
ex. cartitem-1 shows cartimage-1
var itemCount=0;
var imgCartCount=0;
if ($('.ajax-cart-row').length) {
// itemize cart rows
$('.ajax-cart-row').each(function() {
itemCount++;
var cartItemNumber = 'cartitem-'+itemCount;
$(this).addClass(cartItemNumber);
$(this).val(itemCount);
console.log('cart numbers loaded');
});
// itemize images in cart
$('.ajax-cart-row img').each(function() {
IMGCount++;
var cartImgs = 'cartimg-'+IMGCount;
$(this).addClass(cartImgs);
$(this).val(IMGCount);
$(this).closest('.ajax-cart-row').find('[class*='+cartImgs+']').show();
console.log('image numbers added');
});
}
edit: There are multiple cartitem-# img elements without any individual classes/ids/filenames to go by. That's what this is for hopefully.
Hopefully I'm not just sleep deprived here... Thanks in advance
I'm not sure exactly what you're going for, or what is wrong with your code (except that "show" simply ensures that the element is not hidden - maybe your images are hidden by default?). See if something like this makes any difference:
var itemCount=0;
if ($('.ajax-cart-row').length) {
// itemize cart rows
$('.ajax-cart-row').each(function() {
itemCount++;
var cartItemNumber = 'cartitem-'+itemCount;
var cartRow = $(this);
cartRow.addClass(cartItemNumber);
cartRow.val(itemCount);
console.log('cart numbers loaded');
// add class to the image subelements (assumes only one, or that the same class is added to all img children of cartitem-#)
var imageIdx = 0;
cartRow.find("img").each(function() {
imageIdx++;
var cartImgs = 'cartimg-'+imageIdx;
var cartImg = $(this);
cartImg.addClass(cartImgs);
cartImg.val(itemCount);
if (imageIdx === itemCount) {
cartImg.show();
}
console.log('image numbers added');
});
});
}
This should ensure that all img children of an itemized .ajax-cart-row will receive the same index in the class name as the row received (i.e. all img tags within cartitem-1 will receive a the cartimg-1 class). I hope that is what you are looking for.
I need to add an event listener to my retweet, like and dislike buttons. They all have the same ID so right now only the top tweet has the counter increase. This is a project for school so I can only use raw JS. Here is a link to the fiddle:
https://jsfiddle.net/1sc7g5ko/
And here is what my JS looks like
var retweets;
retweets = 0;
var likes;
likes = 0;
var dislikes;
dislikes = 0;
document.getElementById("retweet").addEventListener("click", retweetClicked);
function retweetClicked(){
document.getElementById("retweet").innerHTML = retweets += 1;
};
document.getElementById("likes").addEventListener("click", likeClicked);
function likeClicked(){
document.getElementById("likes").innerHTML = likes += 1;
};
document.getElementById("dislikes").addEventListener("click", dislikeClicked);
function dislikeClicked(){
document.getElementById("dislikes").innerHTML = dislikes += 1;
};
Element IDs should be unique within your entire document. If you have more than one element with the same ID, your HTML is invalid.
Source: Can multiple different HTML elements have the same ID if they're different types?
I suggest you use classes instead, which support having multiple elements with the same class.
Then you can use document.getElementsByClassName("name") to get a list of all elements with that class.
What #Maxmillian Laumeister said is correct, but there are other solutions and/or workarounds. For example, let's say you have three <BUTTON> elements with the ID of edit. How you would go about adding event listeners to all of these elements is as such:
First we would grab all of the elements using querySelectorAll
Then, we would loop through with them using forEach
Inside/Using this forEach loop, we would then add the event listeners.
Implementation of this process is below. Feel free to view the demo of this on JSFiddle.
https://jsfiddle.net/n1b2u8cm/
document.querySelectorAll("#edit").forEach((e) => {
e.addEventListener("click", () => {
document.body.style.background = "red";
setTimeout(() => {
document.body.style.background = "blue";
}, 300);
});
});
I want to execute a function repeatedly on groups of predictably named html divs.
I am using a drag and drop relationship shown below in which dragging text into a certain div space "target" causes that text to appear in another div called "saves".
<script type="text/javascript">
function OnDragStart (event) {
if (event.dataTransfer) {
var format = "Text";
var textData = event.dataTransfer.getData (format);
}
}
function OnDropTarget (event) {
if (event.dataTransfer) {
var format = "Text";
var textData = event.dataTransfer.getData (format);
if (!textData) {
textData = "<span style='color:red'>The data transfer contains no text data.</span>";
}
var savesDiv = document.getElementById ("saves");
savesDiv.innerHTML = savesDiv.innerHTML + "<br />" + textData;
}
else {
alert ("Your browser does not support the dataTransfer object.");
}
if (event.stopPropagation) {
event.stopPropagation ();
}
else {
event.cancelBubble = true;
}
return false;
}
</script>
The script in combination with the corresponding html works perfectly for the target and saved divs... but what i would really like is to apply the same script to a set of divs pairs named
(target1, saves1 )
(target2, saves2)
(target3,saves3)
(target4 saves4) etc etc
with numbers in div ids going up every time by 1 up to (target20, saves 20) ... Without obviously repeating the same script 20 times with different id names when referring to all the target and saved divs.
I realize this is a total newbie question but I'm really interested to learn the different ways this can be approached.
Give a common class name to these divs so when the dragdrop event occurs, it can be handled using the class name instead of the id; that is, like $('.someClass').someEvent instead of $('#target1'). You can get its id property inside this function using $(this).attr("id").
So if you have "target1" as the id, get the last character ("1") using the JavaScript substring function; you can write generic code such as this:
$('.someClass').someEvent(function(){
var id=$(this).attr(id);
var lastno=id.substring(id.lastIndexOf("t"),id.length);
//now rest of code
$("#saves"+lastno).val($("#target"+lastno).val());
});
I'm trying to swap select option values with jQuery when a links clicked, at the moment its just resetting the select when the links clicked, not sure what's going wrong?:
jQuery:
$(function () {
$("#swapCurrency").click(function (e) {
var selectOne = $("#currency-from").html();
var selectTwo = $("#currency-to").html();
$("#currency-from").html(selectTwo);
$("#currency-to").html(selectOne);
return false;
});
});
JS Fiddle here: http://jsfiddle.net/tchh2/
I wrote it in a step-by-step way so it is easier to understand:
$("#swapCurrency").click(function (e) {
//get the DOM elements for the selects, store them into variables
var selectOne = $("#currency-from");
var selectTwo = $("#currency-to");
//get all the direct children of the selects (option or optgroup elements)
//and remove them from the DOM but keep events and data (detach)
//and store them into variables
//after this, both selects will be empty
var childrenOne = selectOne.children().detach();
var childrenTwo = selectTwo.children().detach();
//put the children into their new home
childrenOne.appendTo(selectTwo);
childrenTwo.appendTo(selectOne);
return false;
});
jsFiddle Demo
Your approach works with transforming DOM elements to HTML and back. The problem is you lose important information this way, like which element was selected (it is stored in a DOM property, not an HTML attribute, it just gives the starting point).
children()
detach()
appendTo()
That happens because you remove all elements from both <select> fields and put them as new again. To make it working as expected you'd better move the actual elements as follows:
$("#swapCurrency").click(function(e) {
var options = $("#currency-from > option").detach();
$("#currency-to > option").appendTo("#currency-from");
$("#currency-to").append(options);
return false;
});
DEMO: http://jsfiddle.net/tchh2/2/
You are replacing the whole HTML (every option) within the <select>. As long as each select has the same amount of options and they correspond to each other, you can use the selected index property to swap them:
$("#swapCurrency").click(function (e) {
var selOne = document.getElementById('currency-from'),
selTwo = document.getElementById('currency-to');
var selectOne = selOne.selectedIndex;
var selectTwo = selTwo.selectedIndex;
selOne.selectedIndex = selectTwo;
selTwo.selectedIndex = selectOne;
return false;
});
JSFiddle