jQuery click dynamic element - javascript

See the code's comment:
$.each($('input[type="radio"]'), function(){
var input = $(this);
var container = $('<div class="radio"></div>');
var mark = $('<span />');
input.wrap(container).after(mark);
container.click(function(){
alert('test'); // Not triggered.
});
});
The html is:
<input type="radio" value="female" name="gender" />
Anyone know why the alert is not triggered when clicked, and yes it is visible in CSS. When I use :
console.log(container);
It does give me the HTML it is containing.
Thanks

$('body').on('click', 'div.radio', function() {
});
Full Code
$('body').on('click', 'div.radio', function() {
alert('test');
});
$.each($('input[type="radio"]'), function(){
var input = $(this);
var container = $('<div class="radio"></div>');
var mark = $('<span />');
input.wrap(container).after(mark);
});
NOTE
Instead of body, you should use a static-element that is the container of container.
Why you need this
You need delegate event handler, as your element added to DOM dynamically that means. after page load.

after some tested it seems to me that the "wrap" clone the object you pass it as argument, or reference to the object is lost but I'm not so sure.
a first solution is to assign the event "onclick" before moving the object in the "wrap".
$.each($('input[type="radio"]'), function(){
var input = $(this);
var container = $('<div class="radio"></div>');
var mark = $('<span />');
$(container).click(function(){
alert('test'); // triggered now.
});
input.wrap(container).after(mark);
});
a simplified version :
$.each($('input[type="radio"]'), function(){
var wrapper = $('<div class="radio"></div>').click(function(){
alert('test'); // triggered now.
});
$(this).wrap(wrapper).after($('<span />'));
});
dont forget to decalare this function in the onload function
$(function(){
// your code here ....
});

I was also affected by this and found that on is available only with jquery 1.7 and above.
I am on jquery 1.4.1 and on is not available with version. Upgrading jquery was something I wanted to avoid.
Thankfully delegate was there and it solved the problem.

Related

Remove parent and everything inside it?

I'm trying to use jQuery to remove a div and all of its content when a child div is clicked. To explain this, here is a working FIDDLE. Basically I need to remove the pDiv when the close button is clicked. So I tried this:
$('div').on('click', '.closeDiv', function () {
$(this).prev().remove();
$(this).remove();
$(this).parent().remove();
$('#upload-file').val("");
});
However this doesn't seem to delete the pDiv.
Please test the FIDDLE above buy adding an image and then click on the Green close button and then try to add another image and you will see that the previous pDiv hasn't been removed.
Could someone please advice on this issue?
Thanks in advance
The issue is because you call $(this).remove() before you try and do further DOM traversal on the element which no longer exists. Remove that line. Note that you can also just use closest() to find the required .pDiv element, then remove it, like this:
$('#thumbnail').on('click', '.closeDiv', function() {
$(this).closest('.pDiv').remove();
});
Also note that the code in your fiddle uses an odd mix of jQuery and native JS. You should stick to one or the other. You're also doing several processes which aren't needed, such as creating a canvas element. Try this:
jQuery(function($) {
var $thumbnail = $('#thumbnail').on('click', '.closeDiv', function() {
$(this).closest('.pDiv').remove();
$('#upload-file').val('');
});
var $fileDiv = $("#upload");
var $fileInput = $("#upload-file").on('change', function(e) {
var filesVAR = this.files;
showThumbnail(filesVAR);
});
function showThumbnail(files) {
var file = files[0]
var $pDiv = $('<div class="pDiv" />').appendTo($thumbnail);
var $image = $('<img class="imgKLIK5" />').appendTo($pDiv);
var $div = $('<div class="closeDiv">X</div>').appendTo($pDiv);
var reader = new FileReader()
reader.onload = (function(aImg) {
return function(e) {
aImg.src = e.target.result;
};
}($image[0]))
var ret = reader.readAsDataURL(file);
}
});
Updated fiddle
try following and follow the comment i mentioned.
$(document).on('click', '.closeDiv', function () {
$(this).prev().remove(); // i don't know why you need this.. let us know your structure
//$(this).remove(); you don't need this line
$(this).parent().remove();
$('#upload-file').val("");
});
Please find the working Fiddle for this

Why is jQuery .click() is skipped over?

I have a small script of javascript which iterates over a set of checkboxes which grabs the name attribute and value and then convert it to json. Then I use that value to set the href of an element and then try to trigger a click.
For some reason everything seems to function properly except for the click. I successfully change the href, I console.log() a value before the .click() and after. Everything hits except for the click. The url in the href is value as I clicked it manually.
I have my script included just before the closing body tag and have it wrapped in $(document).ready(). and I do not have duplicate ID's (I viewed the rendered source to check)
Can anyone offer some insight on this?
Here is the javascript
$(document).ready(function() {
$("#multiExport" ).on('click', function(e){
e.preventDefault();
var i = 0;
var list = new Array();
$('.appSelect:checked').each(function(){
var name = $(this).attr('name');
var id = $(this).val();
list[i] = new Array(name, id);
i++;
});
var serList = JSON.stringify(list);
console.log(serList);
var webRoot = $("#webRoot").text();
$("#exportLink").attr('href', webRoot+"/admin/admin_export_multiExport.php?emailList="+serList); //hits
console.log('1'); //hits
$("#exportLink").click(); //this line never executes
console.log('2'); //hits
});
});
$(selector).click() won't actually follow the link the way clicking on it with your mouse will. If that's what you want, you should unwrap the jquery object from the element.
$(selector)[0].click();
Otherwise, all you're doing is triggering event handlers that may or may not exist.
I may guess you need
$(document).on('click', '#multiExport', function(e){
(you can replace document by a nearest element, if you got one).
if you need dynamic click event binding.
EDIT
I would try something like that :
$(document).ready(function() {
$("#exportLink").click(function() {
window.location = $(this).attr('href');
});
$("#multiExport" ).on('click', function(e){
//whatever you want
$('#exportLink').attr('href', 'something').trigger('click');
});
});
$("#exportLink").click(); // this would launch the event.
I must admit I am very surprised that the .click() does not work.
If the idea is to load the page, then the alternative is
$(function() {
$("#multiExport" ).on('click', function(e){
e.preventDefault();
var list = [];
$('.appSelect:checked').each(function(){
var name = $(this).attr('name');
var val = $(this).val();
list.push([name, val]);
});
var serList = JSON.stringify(list);
var webRoot = $("#webRoot").text();
location=webRoot+"/admin/admin_export_multiExport.php?emailList="+serList;
});
});

Assign click-event on a new element in the event itself

I want to create a new element and assign this element the same event for onclick, which it has created it.
DEMO
$(function(){
var counter = 0;
$('.sub').click(function(event){
event.stopPropagation();
counter++;
$div = $(this); // makes more sense in the original code
$div.append('<div class="sub" title="subsub">subsub' + counter + '</div>');
//$div.find('.sub').click // <-- ?????
});
});
In my demo I want to create a new subsub for every sub, which was clicked. Than I want to add the same click event to the new subsub element.
Could anyone help me with this?
I've found nothing for this problem. Maybe I don't have the correct keywords for google or SO :/
Just use event Delegation
$(document).on('click', '.sub', function(event){
Your click events seem to be working correctly at this point,because you are using append which actually nests the new div inside the div that is clicked. Try using after and the functionality breaks.
$(function(){
var counter = 0;
$(document).on('click', '.sub', function(event){
event.stopPropagation();
counter++;
$div = $(this); // makes more sense in the original code
$div.after('<div class="sub" title="subsub">subsub' + counter + '</div>');
});
});
Check Fiddle
Why not create proper elements instead :
$(function(){
var counter = 0;
$('.sub').on('click', doStuff);
function doStuff(event) {
event.stopPropagation();
counter++;
var $div = $(this),
$sub = $('<div />', {'class':'sub',
title : 'subsub',
text : 'subsub' + counter,
on : {
click : doStuff
}
}
);
$div.append($sub);
}
});

jQuery Bind each() and also click() on the same function

So I have the following fragment:
$(".server").each(function() {
var element = $(this);
//bunch of javascript here with element
});
I also want to bind a single click event for an id to do the same work as the above, how is this possible, without copying and pasting the entire block and doing:
$("#my-id").click(function() {
var element = $(this);
//bunch of javascript here with element
});
I think the following should work:
var eventHandler = function() {
var element = $(this);
//bunch of javascript here with element
};
$(".server").each(eventHandler);
$("#my-id").click(eventHandler);

Hooking events with .on() with JQUERY

I want to hook events with the .on() method. The problem is I don't know how to get the object reference of the element on which the event take place. Maybe it's a midunderstanding of how the method really works... but I hope you can help.
Here's what I want to do:
When a file is selected, I want the path to be displayed in a div
<div class="wrapper">
<input type="file" class="finput" />
<div class="fpath">No file!</div>
</div>
Here's my script
$(document).ready(function() {
$this = $(this);
$this.on("change", ".finput", {}, function() {
var path = $(this).val()
$(this).parents().children(".fpath").html(path.split("\\").pop());
});
});
Something like that but that way it doesn't work.
Like this
$(document).ready(function() {
$('.finput').on("change", function() {
var path = $(this).val()
$(this).parents().children(".fpath").html(path.split("\\").pop());
});
});
Do you need to use on()? I'm not sure what you are trying to do exactly.
$("#wrapper").on("change", ".finput", function(event){
var path = $(this).val()
$(this).parents().children(".fpath").html(path.split("\\").pop());
});
I haven't tested your code, but you need to attach the on() to the wrapper.
Can you just use change()?
$('.finput').change(function() {
var path = $(this).val()
$(this).parents().children(".fpath").html(path.split("\\").pop());
});
This should help. If you want to see when a file input changes, bind the event to it
$("input[type='file']").on("change", function(e){
var path = $(this).val();
})
Try:
$(document).ready(function() {
$('body').on('change','input.finput', function() {
var path = $(this).val()
$(this).parent().children(".fpath").html(path.split("\\").pop());
});
});
$(document).on("change", ".finput", function() {
$(".fpath").html(this.value.split("\\").pop());
});
This is a delegated event handler, meaning the .finput element has been inserted dynamically so we need to delegate the listening to a parent element.
If the .finput element is not inserted with Ajax and is present on page load, you should use something like this instead:
$(".finput").on("change", function() {
$(".fpath").html(this.value.split("\\").pop());
});

Categories