I am dynamically loading some of the content within my page and would like to get a total of all the data-attributes.
First the elements are cloned and appended
$('.chip').on('click', function () {
$(this).clone().appendTo('.chipPlacement');
});
Then I have written a function that should get the totals
function chipsBet() {
var redchip = $('.chipPlacement .chipValue.r').data() || 0;
var bluechip = $('.chipPlacement .chipValue.b').data() || 0;
var orangechip = $('.chipPlacement .chipValue.o').data() || 0;
var total = redchip.chipValue + bluechip.chipValue + orangechip.chipValue;
return total;
}
Before I append the elements the HTML looks like
<div class="chipPlacement"></div>
and once appended the HTML structure is
<div class="chipPlacement">
<div class="chip red">
<div class="chipValue r" data-chip-value="1">1</div>
</div>
</div>
I need to listen for the DOM structure the change and then fire the chipsBet() function, but I'm not sure how to get this to work. I can't use .on('change') as that only applies to input, textarea and select.
I have tried firing the chipsBet function within the .chip.on('click') but I get NaN returned.
How can I get the data-attribute-values for the new elements in the DOM?
If you don't have a blue or orange chip, you're effectively trying to get .chipValue from 0 which is undefined and adding it to another number gives you NaN.
You can simply iterate over all .chipValue elements within the placement element like so:
function chipsBet()
{
var total = 0;
$('.chipPlacement .chipValue').each(function() {
total += $(this).data('chipValue');
});
return total;
}
Nevermind, you altered your initial question.. carrying on.
<div class='chipPlacement'>
<div class='chip red'>
<div class='chipValue' data-chip-value='1'></div>
</div>
</div>
Then to read your data attributes, you could do something like this.
$('.chip').on('click', function () {
$(this).clone().appendTo('.chipPlacement');
chipsBet();
});
function chipsBet() {
var redchipVal = parseInt($('.chipValue .r').data('chip-value')) || 0;
var bluechipVal = parseInt($('.chipValue .b').data('chip-value')) || 0;
var orangechipVal = parseInt($('.chipValue .o').data('chip-value')) || 0;
var total = redchipVal + bluechipVal + orangechipVal;
return total;
}
I think you want something like bellow. It will call the function every time any change will in div .chipPlacement.
$('.chipPlacement').bind("DOMSubtreeModified",function(){
console.log('Div modified');
});
You can say for your problem
$('.chipPlacement').bind("DOMSubtreeModified",function(){
chipsBet();
});
DEMO
Related
how can i update the contents of a dynamically created div as i type into an input field that was also created dynamically.
First i have an input that requests the number of code blocks i want:
$("#count-trigger").click(function(){
var count = $("#slide-count").val();
if (count !== "" && $.isNumeric(count)) {
var i = 1;
while (i <= count) {
$('.appendHere').append(
// Div I want to write to.
'<div 'id="slide-content_'+i+'">'Sample Title </div>'+
// Input field used to populate above div
' <input '+
' type = "text" '+
' name = "slide_name_'+i+'" '+
' data-target = "slide_name_'+i+'" '+
));
i++;
}
});
The above is pretty obvious, enter in a value press go and i get x number of divs/inputs.
Problem comes when trying to populate a created div as I type into created input.
Any help would be greatly appreciated.
You can use an IIFE to keep a scope for each iteration and use variables that are consumed later. In latest ECMA, you can even make use of block level scope for the same.
$("#count-trigger").click(function() {
var count = $("#slide-count").val();
var i = 1;
while (i <= count) {
(function() {
var codeOutput, codeInput;
codeOutput = $('<div class="code">');
codeInput = $('<input type="text"/>');
codeInput.on('input', function() {
codeOutput.text($(this).val())
})
$('.appendHere').append(codeInput, codeOutput);
})();
i++;
}
});
.code {
border: 1px dashed #bc0000;
min-height: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="slide-count" type="number" />
<button id="count-trigger">Create</button>
<div class="appendHere"></div>
Okay, so the change suggested from #zak did the trick.
I added a onchange="liveUpdate(input_id)" to each input.
and then add this function
function liveUpdate(e_id) {
var typed = $('#'+e_id).val();
$('[data-target='+e_id+']').text(typed);
}
I imagine there is a better solution to this but considering how much I suck at js and the fact that it works perfectly --I am happy with.
I have the following code, the alert works fine. the div refreshes fine, the var is not returned what am I missing, thanks
$('.cap_per_day').blur(function () {
var sum = 0;
var remaining = 0;
$('.cap_per_day').each(function() {
if ($(this).val() != "") {
sum += parseFloat($(this).val());
remaining = total - sum;
}
});
//alert('Total Remaining '+ remaining);
$(document.getElementById('div.alert-div')).innerHTML = remaining;
$("div.alert-div").fadeIn(300).delay(2000).fadeOut(400);
});
It's not clear exactly what the problem you're trying to solve is, however from your code sample I can tell you that a jQuery object doesn't have an innerHTML property, and the 'id' selector looks more like a class. Try this instead:
$('div.alert-div').html(remaining);
I'm having some trouble with jQuery in Meteor - I'm just trying to learn so I hope someone could help.
So when #addButton is clicked it will append the div to the .formField and each div created on click will have an unique class, eg formField[1], formField[2] etc
The trouble is when the button is clicked instead of just changing the name of the div only, the div is also added 50 times. I know how dumb it sounds as its a loop, but how would I loop only the div's class on click so each have a different name?
My code is below:
Template.form.events({
'click #addButton': function(event) {
var i;
for (i = 0; i < 50; i++) {
$(".formField").append('<div class="formField['+i+']">.....</div>');
}
return false;
If I understand what you are doing here you don't need a loop. You just need a variable to increment every time the button is clicked. Take your append out of the loop and instead on click increment your variable by one then call an append. No loop necessary.
var i = 0;
Template.form.events({
'click #addButton': function(event) {
i += 1;
$(".formField").append('<div class="formField['+i+']">.....</div>');
}
});
return false;
Do it like this, (i.e. by creating a closure), click run to verify
var uuid = 0;
$('#addButton').on('click', function (event) {
uuid = uuid + 1;
$(".formField").append('<div class="formField[' + uuid + ']">Form' + uuid + '</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="formField"></div>
<input type="button" value="Add New" id="addButton"></input>
The idea of this script is to allow dynamically created elements to respond to a keyup function that changes the inner html (or jQuery text()) based on what is inside of a text form.
Each dynamically created element has it's own text form and title. So whatever you type in that given element's text form should become the title for that element which is wrapped in tags.
I've tried a few ways but I just cant get it to work. What is the best way to go about this?
Here's my latest attempt - http://jsfiddle.net/gnkxxgjz/1/
$('body').on('keyup', '.qForms', function() {
var nameOfLoan = [];
var loanOfName = function(t) {
if ($(this).hasClass('.loanNameV'+t)) {
$('body').on('keyup', '.qForms', function() {
var loanN = $('.loanNameV'+t).val();
$('.nameLoan'+t).text(loanN);
});
}
else {
return false;
}
};
for (var t=1; t < z; t++) {
nameOfLoan[t] = loanOfName(t);
}
for (var j=1; j < z; j++) {
nameOfLoan[j]();
}
});
Take a look at this Fiddle
<button onclick="crea()">create</button>
<div id="d1">
</div>
function crea(){
$('#d1').append( $("<h2></h2><input>").on('keyup',function(){
$(this).prev().html( $(this).val() );
}) )
}
Something along these lines:
$(document).on("keypress", $("input"), function(e){
console.log($(e.target).attr("id"))
});
This will print to the console the id attribute of any input field you type into. Please provide how the input and text elements are related and I might be able to link them in this code piece.
I'm trying to make a game where you click a button to earn a point. Once you obtain X amount of points a div appears. I tired using jquery's .change to see if #pointCounter has changed in order to know if the new div should appear (by adding the new class). This isn't working though. Am I not using the change method correctly, or should I use something else? Is there a to check when the var points changes instead of checking if the html changes?
HTML
<p>You have <span id='pointCounter'>0</span> points.</p>
<button id='clickButton'>Click Me</button>
<div id='store'></div>
JS
$('#clickButton').click(function() {
points = points + addPoints;
$('#pointCounter').html(points);
});
$('#pointCounter').change(function() {
if (points >= 5) {
$('#store').addClass('showMe');
}
});
Is it not possible to display the div at this point:
$('#clickButton').click(function() {
points = points + addPoints;
if (points > 500) $('#someDIV').addClass('showme');
$('#pointCounter').html(points);
});
Change is just for selects or other form elements as j08691 said but you could do something like this, right now I just have points set as a global var but you could also pass a value into the function to increment the points value.
See it in action: http://jsfiddle.net/1j33tm0g/1/
var points = 0;
var addPoints = 1;
$('#clickButton').click(function() {
points += addPoints;
$('#pointCounter').html(points);
if(points >= 5) {
$('#store').addClass('showMe');
}
});
I would go with jQuery hide/show:
<p>You have <span id='pointCounter'>0</span> points.</p>
<button id='clickButton'>Click Me</button>
<div id='store'>Test</div>
And using the JS:
var points = 0;
var addPoints = 1;
$("#store").hide();
$('#clickButton').click(function() {
points = points + addPoints;
$('#pointCounter').html(points);
if (points >= 5) {
$('#store').show();
}
});
Here: http://jsfiddle.net/rnm9e5vh/