jQuery - add functionality to element after load() - javascript

I have some code which loads some html from another file, which works as it should. But I am struggling to access elements from this newly loaded data.
I have this code:
var widgetSettings = $("<div>").addClass("widgetsettings").load('dashboard/chart-settings-form.php #editChartForm');
widgetSettings.appendTo(widget.element);
//so far so good...
widget.element.find('.date').each(function(i){
$(this).datetimepicker(); //this doesn't work
console.log('testing... '+$(this).attr('id')); //this doesn't even work...
});
I'd expect it to find these text boxes in the '#editChartForm' form loaded from the above url (they're within a table):
<input type="text" name="datefrom" id="datefrom" class="date" /> To: <input type="text" name="dateto" id="dateto" class="date" />
The html is definitely being loaded. Just really confused as to why I can't access any elements from the load() event.
I also wanted to apply a click function to a cancel button on the same form, and I found the only way to make it work was to put it within a 'live' function before the load:
$('.cancel').live('click', function() {
//actions here...
});
Any ideas what is going on?

Simple! Because the load() method is asynchronous, and your line widget.element.find('.date') is firing BEFORE there's actually any elements in the DOM that match it! Just use a callback in your load(), like this:
$("<div>").addClass("widgetsettings").load('dashboard/chart-settings-form.php #editChartForm', function() {
$('div.widgetsettings').find('.date').each(function(i){
$(this).datetimepicker();
console.log('testing... '+$(this).attr('id'));
});
});

$("div").load("url here",function(){
callbacks();
});
function callbacks(){
//put everything that you want to run after the load in here.
//also if the click function is in here it wont need the .live call
}
Edit: Also with the latest version of jQuery you can now use .on instead of .live (its much more efficient) ie.
$(".widgetsettings").on("click",".cancel",function(){
//actions here
});
hope this helps :)

Related

jQuery .click() not working (debugging)

I am new to jQuery and am making a few .click() functions for my website, but no matter what I try, I can't get them to work.
jquery:
$(document).ready(function(){
$("#underlay-img-container-btns-add").click(function(){$("#underlay-img-container-form-file").click();});
$("#underlay-img-container-btns-submit").click(function(){document.forms['underlay-img-container-form'].submit();$("#underlay-img-container-general_loader").css("display","inline-block");});
$("#underlay-img-container-form-file").change(function(){readURLImg(this);});
$("#underlay-gif-container-btns-add").click(function(){$("#underlay-gif-container-form-file").click();});
$("#underlay-gif-container-btns-submit").click(function(){document.forms['underlay-gif-container-form'].submit();$("#underlay-gif-container-general_loader").css("display","inline-block");});
$("#underlay-gif-container-form-file").change(function(){readURLImg(this);});
});
readURLImg (displays an image preview before submission. This is part of a file uploading script.):
function readURLImg(input){if(input.files&&input.files[0]){var reader=new FileReader();reader.onload=function(e){$("#underlay-img-container-preview").attr("style","background-image:url("+e.target.result+");color:#fafafa");}
reader.readAsDataURL(input.files[0]);}}
I am sure my ids are correct. I have been trying to find the answer for hours with no success.
i have checked your website
then I've clicked on button upload you picture > opened the terminal and test
$("#underlay-img-container-btns-add").click(function(){alert('btn clicked')})
and the results appears
So, your problem is to call the events when the popups are ready
to Understand the concept
close the popup and try the same code it will retrieve empty array '[]'
<div class="btn" id="green" >
<div class="icon-image"></div>
<span>Upload your picture</span>
</div>
and add
$('.btn#green').click(function() {
$('.overlay').html($('.overlay').html().replace(/!non_select_tag!/g, 'img'));
$('.overlay').html($('.overlay').html().replace(/!non_select_txt!/g, 'Picture'));
// add you events
$("#underlay-img-container-btns-add").click(function(){alert('btn clicked')})
$('.overlay').show();
})
this will work
try
$("#underlay-img-container-btns-add").on( 'click', function () { ... });
may not work because content is dynamically created.
try
$("#underlay-img-container-btns-add").bind( 'click', function () { ... });
To bind events to dynamically generated elements in DOM, you may use
$('document').on( 'click', '#selector', function () {
...
});
This binds event to the DOM rather than to the element directly, which may not exist all the time.
try
$("body").delegate("#underlay-img-container-btns-add",'click',function(){
....
});

.click() not working when using jQuery

I have a normal js script which has been working since the start of my project. But now for some reason when I click on buttons nothing works at all, no response from the clicking event(note this used to work) and nothing displays in the console log stating if there is an error of some sort... the script just doesn't respond...
Here is the HTML:
<script type="text/javascript" src="js/myscript.js"></script>
<form>
<input type="text" name="signinemail" id="signinemail" placeholder="Enter Email">
<input type="password" name="signinpassword" id="signinpassword" placeholder="Enter Password">
<input type="submit" id ="siginsubmit" name="siginsubmit" value="Sign In">
</form>
Here is my javascript:
$(document).on('pageinit',"#sellbookpage",
function()
{
$("#siginsubmit").click
(
function()
{
alert("hello");
}
);
}
);
Note I am making use of jQuery Mobile
The pageinit event is only available if you use jQuery Mobile. Are you still using that? Otherwise you should use $(document).ready( ... ).
The winning answer to my problem was nothing to do with any of the above posts mentioned above! What was causing the problem was I was using the jQuery mobile, jQuery and Twitter Bootstrap. As soon as I commented out the link to the bootstrap css everything started to work as it used to. Thus there must be a conflict between Twitters Bootstrap and either jQuery or jQuery Mobile.
have u tried using live()
$("#sellbookpage").live('pageinit', function() {
$("#siginsubmit").click(function(){
alert("hello");
});
});
From http://api.jquery.com/on/#on-events-selector-data-handlereventObject:
When a selector is provided, the event handler is referred to as
delegated. The handler is not called when the event occurs directly on
the bound element, but only for descendants (inner elements) that
match the selector. jQuery bubbles the event from the event target up
to the element where the handler is attached (i.e., innermost to
outermost element) and runs the handler for any elements along that
path matching the selector.
siginsubmit is an input (which cannot contain descendant elements let alone descendant elements with id="sellbookpage") so the selector string is not matching anything and the click event is never reaching the siginsubmit input.
Change it to this:
$(document).on('pageinit', function () {
$('#siginsubmit').click(function (e) {
alert('hello');
e.preventDefault();
return false;
});
});
Working fiddle: http://jsfiddle.net/VG3Eg/

Event at value changed using jquery.val()

I have an <input type="text"> that have you value updated for many other scripts jQuerys, using the method .val("value here"). I need a new script to be run when the value of input has been updated. How to associate an event that'd make it for me?
Here is my code:
$('#PedidoTotalDescontoPadrao').change(function()
{
console.log('test');
});
but it doesn't work
I think you're using the wrong event handler for what you need.
Try this one.
http://api.jquery.com/keyup/
The change() method does not applies to <input type="text"> html tags. you may wan't to do it with keyup().
$('#PedidoTotalDescontoPadrao').keyup(function() {
console.log('test');
// and this is how you'd trigger the other events you want
$('.something').trigger('click');
});

Javascript doesn't work on elements added by jquery's load(), prepend(), or append() functions

I have a comment system where a user submits a comment, the comment is processed, then the HTML for the comment is returned. jquery then adds that retrieved HTML to the comment system. that whole system works, but the comment buttons that requir javascript do not work unless I refresh the page. How do make my javascript work on elements added through load, prepend, or append?
Not sure if my question is clear, but here's the javascript I have:
$(function () {
$(".replyform").submit( function (event) {
event.preventDefault();
id = $(this).attr("id").split('_')[1];
text = $('textarea#text_'+id).val();
$.post( "/api/add/comment/", {_csrf: _csrf, id: id, text: text, a: a},
function (data) {
$('#commentreplies_'+id).prepend(data);
$('#replyform_' + id).hide();
});
});
});
I then have elements such as "reply" for each comment that have functions in an external javascript that do not work unless I refresh the page. Hopefully that made sense.
Use jQuery live() (it is deprecated, see on()) function
jQuery has a live method to allow elements that are added on the page after loading to be able to have events already bound by jQuery. You can bind your events using live method as described here.
A second solution, and probably a more efficient one, would be using delegate method to handle events by existing containers and delegating them to the elements inside that container. You can read more about delegate here.
An example solution using live method is as follows assuming you have buttons with class 'reply' in your response data:
$(".reply").live('click', function(event) {
event.preventDefault();
id = $(this).attr("id").split('_')[1];
text = $('textarea#text_'+id).val();
// post won't work since url is missing, but that code remains the same.
// Assuming you get a response like this
// <div><input type="textarea" id="text2" /><input type="submit" id="reply_2" value="submitReply" class="reply" /></div>
// And if you append this to your document
var data = $('<div></div>').html('<input type="textarea" id="text2" /><input type="submit" id="reply_2" value="submitReply" class="reply" />');
$('#commentreplies_'+id).prepend();
$('#reply_' + id).hide();
});
There are few different approaches to this
1) Explicitly init the button inside returned HTML on AJAX success
2) Setup global handler for your button type using jQuery live() function (replaced by on() in 1.7)
3) define button handler right in the markup
Which one do you pick is really up to your specific task.

jQuery Class selector not working

I'm struggling to make an alert come up when an anchor tag with a specific class is clicked inside of a div.
My html section in question looks like this...
<div id="foo">
<a class='bar' href='#'>Next</a>
</div>
The jQuery section is as follows..
$('.bar').click(function()
{
alert("CLICKED");
});
My problem is that I cannot get this alert to come up, I think that I'm properly selecting the class "next", but it won't pick it up for some reason. I've also tried almost everything on this page but nothing is working. If I don't try to specify the anchor tag i.e. $('#foo').click(function()... then it works, but there will be multiple anchor tags within this div, so simply having the alert executed when the div is clicked won't work for what I need. The website this is on is a search engine using ajax to send information to do_search.php. Within the do_search.php I make pagination decisions based on how many results are found, and if applicable, a next, previous, last, and first link may be made and echoed.
EDIT: I just figured it out, it was my placement of the .next function, since it wasn't created on the initial document load but instead after a result had been returned, I moved the .next function to the success part of the ajax function since that is where the buttons will be created if they need to be, now it works.
Try using the live() command:
$(".bar").live("click", function(){ alert(); });
Because you load your button via AJAX, the click event isn't binded to it. If you use the live() command, it will automatically bind events to all elements created after the page has loaded.
More details, here
.live is now deprecated and is the selected answer for this. The answer is in the comments in the selected answer above. Here is the solution that resolved it for me:
$(document).on('click','.bar', function() { alert(); });
Thanks to #Blazemonger for the fix.
You surely missed $(document).ready(). Your code should be:
$(document).ready(function(){
$('.bar').click(function()
{
alert("CLICKED");
});
});
Hope this helps. Cheers
Make sure you have included JQuery Library properly.
Make sure your script has written between $(document).ready() in short $(function(){ });
Demo : http://jsfiddle.net/W9PXG/1/
<div id="foo">
<a class='bar' href='#'>Next</a>
</div>
$(function(){
$('a.bar').click(function()
{
alert("CLICKED");
});
});

Categories

Resources