Using .each on dynamic objects in jQuery? - javascript

There are lots of questions that seem to be asking this, but in the end all they want is to attach .click events and not .each and so the generally accepted answer in all of them include $("body").on("click", ".selector", function(){}); and this is definitely not what I want.
I have some generated inputs and I need to change the value of each one at the same time. Normally I would $(".inputs").each(function(){$(this).val("new-value")}; or something along those lines, however, I can't because of the dynamic aspect.
So how would you do a $("body").on("each", ".inputs", function(){});?

Actually, it's as simple as running the .each inside setTimout.
setTimeout(function(){
$(".inputs").each(function(){$(this).val("new-value")});
}, 5000);

$.each works with any new elements added.
http://jsfiddle.net/4SV7n/
Doing something different each time:
http://jsfiddle.net/4SV7n/1/

Here is much better script that does exactly what the OP asked.
function doWithInput(i, e){
$(e).val("done with each");
}
$(document).ready(function(){
$("#button").click(function(){
$("#inputs").append("<input class='inputs_new' type='text' /><br />");
});
$(".inputs").each(doWithInput);
});
$(document).on("DOMNodeInserted", ".inputs_new", function(e) {
$(e.target).removeClass('inputs_new').addClass('inputs');
doWithInput(0, e.target);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inputs">
<input class="inputs" type="text" placeholder='type in me' /><br />
</div>
<button type="button" id="button">Add</button>

You can use $(".inputs").each(function(){$(this).val("new-value")}; perfectly fine on dynamic elements. You just need to rerun the script after you added an element dynamically.
From the comments I figured that some misunderstanding exists about 'each'. 'Each' is not an event and so no event is fired if 'each' is called. If you want to keep track of added elements because you have no control over when they are added you'd need a timer:
setInterval(function(){ $(".inputs").each(function(){$(this).val("new-value")}; },500);

What about this:
http://jsfiddle.net/cudts0f2/
I want the dynamically generated text to take effect on each

Related

Can't figure out why my change(...) event handler isn't working in this scenario

The relevant piece of HTML is like
<tbody id="results">
<tr>
<td>
<input type="checkbox">
c:\users\me\documents\visual studio 2013\Projects\myproj\Assets/someorg-somecategory-somepic.png
</td>
<td>someorg</td>
<td>somecategory</td>
<td>somepic.png</td>
</tr>
</tbody>
My intent is for the a elements next to the input elements to be visible or hidden depending on whether or not the input is checked.
Seems like it should be simple enough:
$('#results input').change(function() {
console.log("ok, this function got called.");
this.siblings('a').toggleClass('hidden');
});
inside a $(function() { ... });
But, that's not working. Nothing is being printed to the console when I test by checking or unchecking the element. Any idea why this might be? Need me to post any more code?
Add an id to the checkbox or class
<input type="checkbox" id="checkbox"/>
And use $(this) not this
$(this).siblings('a').toggleClass('hidden');
Working demo: http://jsfiddle.net/omnzocqq/
update
According to my idea, you forget to put the table wrap to tbody. But if you add your table wrapper element and edit this to $(this), your code works.
So you don't need to add a class or id to your checkbox.
http://jsfiddle.net/omnzocqq/3/
Demo
The issue is because within the handler this is a DOMElement. You need to wrap this in a jQuery object to be able to call jQuery methods on it:
$('#results input').change(function() {
$(this).siblings('a').toggleClass('hidden');
});
Example fiddle

set event function trigger in looping with jquery

I would like to ask something about set event trigger with jquery.
First of all, i have a form with many buttons ( btnadd1 , btnadd2, btnadd3 , ... )
I have this code:
for(i=1;i=<3;i++){
$('.btnAdd'+i).click(function(){
alert(i);
});
}
The code should be alert(1) when i click btnadd1 , alert(2) when i click btnadd2,
but the problem is when i click btnadd1, btnadd2, or btnadd3 it alerts "3"
My assumption is that the function overwrites the previous function. Does anyone have a solution for this problem?
This is a common closure issue. You can work around it like this:
$('.btnAdd'+i).click(function(idx){
return function(){alert(idx);};
}(i));
JSFIDDLE
The issue deals with closure inside loop.
Better you could use a user defined attribute in your button and use a single classs for binding the event. see #bipen's answer.
<button class= "someclass" data-value="1"> click</button>
<button class= "someclass" data-value="2">click </button>
$('.someclass').click(function(){
alert($(this).attr('data-value'));
});
Check Fiddle
http://jsfiddle.net/hoja/3jt5furd/5/
Avoid using closure inside a loop...better is to assign a single class to all the buttons and register single event for that..make use of data attributes.
$('.someclass').click(function() {
alert($(this).data('value')); //using jquery's data function
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="someclass" data-value="1">
button1
</button>
<button class="someclass" data-value="2">
button2
</button>
there are other solution to achieve what you want, using attribute selector [class^="btnadd"] and so on but i think this solution is better and readable.

Dynamic checkbox onchange & javascript

This might be an easy one for you, but I'm stuck, so I hope you can help me.
I'm creating checkboxes through a loop and want to specify a text somewhere in the website if a checkbox is clicked.
I'v seen solutions where a make a script for each checkbox, but that could turn out to be alot sometimes (something like this: chckbx.onchange = function(){} )
I'd rather have one function that is called from different checkboxes, but my javascript skills is basicly non-existing :)
This is what i got so far (which ofcourse dosn't work)
http://jsfiddle.net/Sz3BK/130/
You have jQuery tagged in your question, so I'm going to provide a jQuery answer:
You'd use jQuery's on() method to delegate the event to a non-dynamic ancestor of your checkbox:
$('elem').on('change', 'input[type="checkbox"]', function() {
...
});
Where elem is a non-dynamic ancestor of your checkbox.
In your JSFiddle your checkbox isn't dynamic, but assuming it was, the closest non-dynamic ancestor of it would be the document's body. Therefore, we can use:
$('body').on('change', 'input[type="checkbox"]', function() {
testing('hello', '1');
});
JSFiddle demo.
You may want to extend this by passing in "hello" and "1" as data-* attributes:
<input type="checkbox" name="test" data-newvalue="hello" data-spanid="1" />
<input type="checkbox" name="test" data-newvalue="second" data-spanid="2" />
Here I've created two checkboxes with our two data-* attributes. In our jQuery method we can pull these values and pass them into our testing() function using jQuery's data() method:
$('body').on('change', 'input[type="checkbox"]', function() {
testing($(this).data('newvalue'), $(this).data('spanid'));
});
JSFiddle demo.
We can then modify our testing() function to also use jQuery:
function testing(newValue, spanID) {
$('#'+spanID).text(newValue);
}
This pulls our spanID (e.g. "1") and places it within an ID selector $('#1'), then modifies the text using jQuery's text() method. If you wanted to modify the HTML instead, jQuery also has a html() method for this purpose.
Final JSFiddle demo.
because you are adding che checkboxes dynamicly,
to enable the change event for those added later, use code below
$(document).on('change', 'input[type="checkbox"]', function() {
...
});
Change your jsfiddle code http://jsfiddle.net/Sz3BK/136/ like this...
Add <head></head> in HTML code at top..
and change on load to "No wrap - in head"
This code works fine for me:
$('input[name=test]').change(function(){
if($(this).is(':checked'))
{
alert("chk");
// Checkbox is checked.
}
else
{
alert("unchk");
// Checkbox is not checked.
}
});
Check the fiddle. Hope it helps.

Clicking on image does nothing

I am trying to create a click event for an image using jQuery but I fail every time I try.
First I have a div:
<div id="price-holder"></div>
then I am using jQuery to insert this HTML by using the following:
$("#price-menu li:nth-child(2)").click(function() {
var pregHTML = $("#cakesmash-price").html();
$("#price-holder").html(pregHTML);
});
However, using this HTML doesn't work
<div id="cakesmash-price" style="display:none">
<img id="cake" src="images/order.png" height="32px" onclick="pregbasic(this);">
</div>
I tried to use the attribute onclick for the image and also tried using jQuery's selector with the ID like so
$("#cake").click(function(){
})
but both didn't work.
Can anyone help me?
Thanks
This assumes that the element is actually being added to the page.
I am betting you are adding the click event before you add the element to the page meaning the selector did not find anything so it did not add the event.
Either add the event after you add the element or use event delegation.
$("#price-holder").html(pregHTML);
$("#cake").click(function(){
});
or
$("#price-holder").on("click", "#cake", function () {
});
Your error could be due to your choice of selectors "#price-menu li:nth-child(2)". Try using the JS .children and .eq selectors. Also if your code was added dynamically consider using the .on() event handler rather than the .click().
Just start with the DOM you actually want, without using jQuery to do this:
<div id="price-holder">
<div id="cakesmash-price" style="display:none">
<img id="cake" src="images/order.png" height="32px">
</div>
</div>
Then you can just add you click handler on #cake:
$('#cake').on('click', function (event) {
// your logic goes here
});

Having a little issue with a simple jQuery fadeOut?

I have a simple ID I want to fadeOut with jQuery after a button. However, when clicking on the respected button it doesn't work and nothing happens. Heres how I get JS file from different location like this:
<script src="http://myflashpics.com/v2/jQuery.js"></script>
<script src="http://myflashpics.com/v2/actions.js"></script>
Here's my action in my actions.js file:
$(document).ready(function() {
$(function() {
$(".profileLink").click(function() {
$("#right_bar_content").fadeOut("slow");
});
});
});
Here's some other HTML assosiated with it:
<img src="http://myflashpics.com/get_image.php?short_string=avqc&size=thumbnail" class="profileLink" />
<div id="right_bar_wrapper" id="right_bar_content">content here</div>
Please help!Coulton
First of all, you shouldn't have two separate ids for your div. Get rid of the right_bar_wrapper id and merge the CSS for the two ids.
Second, $( is just short-hand for $(document).ready; it shouldn't be nested. Remove one or the other.
$(document).ready(function() {
$(".profileLink").click(function() {
$("#right_bar_content").fadeOut("slow");
});
});
You are wrapping your code with DOM ready twice. This shouldn't be an error, but it is not good practice.
Your problem is your div has two id attributes, and the first one being parsed is used in the DOM. I believe a HTML attribute may only ever be used once on the same element.
Get rid of the first id attribute.
Your element can't have two IDs.

Categories