I'm using jQuery form plugin to upload files. The plugin uses a hidden iframe to
upload without refreshing the page. Everything works fine except javascript doesn't work on
generated code. Here's my code:
<form id="image_form" action="" method="post" enctype="multipart/form-data">
<input type="file" id="image_file" name="image_file"><br>
<input type="submit" value="upload">
</form>
<div id="avatar_wrapper">
</div>
This form uploads an image to server and server will return some processed images.
<script type="text/javascript">
$(document).ready(function() {
var options = {
success: showResponse,
dataType: 'html'
};
$('#image_form').ajaxForm(options);
$('.choose_avatar').hover(function() { /* Just for test */
alert('hello');
});
});
function showResponse(responseText, statusText, xhr, $form) {
$('#avatar_wrapper').append(responseText);
}
</script>
responseText contains some images.
<img src="http://localhost/avatar/0.jpg" class="choose_avatar" choice=0>
<img src="http://localhost/avatar/1.jpg" class="choose_avatar" choice=1>
<img src="http://localhost/avatar/2.jpg" class="choose_avatar" choice=2>
I wrote these code to test:
$('.choose_avatar').click(function() { /* Just for test */
alert('hello');
});
It's strange that click function doesn't work on these generated code.
Can someone please help me with this?Thanks.
You will have to use live(), or do it manually, place a click handler on the parent element that is constant, and check event.target to see which one was clicked.
This is how live works under the hood, anyway, so just stick with it :)
Note that if you're using a newer jQuery, then use on() instead of live().
You will have to use .live on these dynamically generated elements.
$('.choose_avatar').live("click", function() { /* Just for test */
alert('hello');
});
On the container avatar_wrapper you must bind a live/delegate listener :
$('#avatar_wrapper').delegate('.choose_avatar','click',function() {
alert('hello');
});
Hope it helps!
When you do a $('.choose_avatar'), you are selecting elements with class choose_avatar (which don't exist yet) and attaching the event handler. Which obviously won't work if the elements are loaded dynamically. A more correct approach is to handle the delegated event on the wrapper div like so,
$('#avatar_wrapper').delegate('img.choose_avatar', 'click', function (e) {
// do stuff
});
Related
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(){
....
});
I'm working with a wordpress theme and I need to activate a button when the page loads, but none of the following has worked for me (my button has the ID "reset"):
$(document).ready(function() {
$("#reset")[0].click();
});
--
$(document).ready(function(){
$("#reset").click();
})
--
$(window).load(function(){
$('#reset').click();
});
I put the code in the header or in the page where i need to activate the button, but does not work.
Thanks!
I give you example here
$(document).ready(function(){
$("#reset").click();
})
the code above should work.
JavaScript does not allow seamless programmatic triggering of an actual click event.
What you could do is
declare the click callback as a separate, named function
e.g.
function myClickCallback(e) {
// Do stuff here
}
Set this as the click callback of your button (e.g. $('#reset').on('click', myClickCallback)).
Invoke the callback when the page loads (e.g. $(document).ready(myClickCallback);)
I am not sure why you 'd want this functionality, since it sounds weird. From reading your description, by "activating", you could also mean enabling the button. To do that you should do something like the following
$(document).on('ready', function (e){
$('#reset').removeAttr('disabled');
});
You may need to refer to it using jQuery instead of $:
The jQuery library included with WordPress is set to the noConflict() mode...
https://codex.wordpress.org/Function_Reference/wp_enqueue_script#jQuery_noConflict_Wrappers
$(document).ready(function(){
$("#reset").trigger('click');
});
Use the function Trigger with the event click
$(document).ready(function(){
$("#reset").trigger('click');
});
This what works for me:
$(function () {
$('#btnUpdatePosition').click();
});
On the button event, the JQuery binding event doesn't work:
$('#btnUpdatePosition').click(function () {
alert('test again');
});
But it works when I added the event on attribute declaration:
<input type="button" value="Update" id="btnUpdatePosition" onclick="alert('Click has been called')" />
You can also call if you have a function on element:
<input type="button" value="Update" id="btnUpdatePosition" onclick="fncShow();" />
I get a strange behaviour. In a web page i import some script and i define some js function.
<script type="text/javascript">
$(function() {
}
</script>
When i click on a button i display a dialog (this block)
I took some info from the server... and insert it in the bookInfoBlock area
Finally i got
<div id="bookDialog" title="book info" style="display:none">
<button type="button" id="addBook1">+</button>
<div id="bookInfoBlock">
<button type="button" id="addBook2">+</button>
</div>
</div>
$('[id^=addBook]').click(function() {
alert("book test");
});
When i click on button with addBook1, i see the alert... but not when i click on addBook2.
It's like this last one don't know the event and javscript
It looks like you're loading addBook2 dynamically via ajax. In that case use event delegation using .on(). If the div bookInfoBlock is static & is present in DOM all the time, use this.
$('#bookInfoBlock').on('click', '[id^=addBook]'), function() {
alert("book test");
});
or if you're not sure about the static parent, use this
$(document.body).on('click', '[id^=addBook]'), function() {
alert("book test");
});
As of jQuery 1.7, the .live() method is deprecated and removed completely in version 1.9. For older versions use .live() instead of on()
$('[id^=addBook]').live('click', function() {
alert("book test");
});
You can use delegate instead of click .
live isn't more used, there is delegate :
$(document).delegate('[id^=addBook]','click', function() {
alert("book test");
});
hey i would like to show an table when user fills an input.
What I have is:
in <head> section:
<script type="text/javascript">
//hide initially
$("table#mytable").hide();
// show function
function showit() {
$("table#mytable").show();
}
</script>
and the table:
<table id="mytable"><tr><td>FOO</td><td>BAR</td></tr></table>
and a form below(maybe it is important) the table:
<form action="foobar.php">
<input name="example" onselect="showit()" />
<input type="submit" value="Send" />
</form>
I think onselect isn't perfect but it should do the thing in my case.
The code above doesn't hide the table at all. I don't know what I did wrong. Hope some1 can find a mistake - thank you.
EDIT
here is the solution:
head:
<script type="text/javascript">
function show(id) {
document.getElementById(id).style.display = 'block';
}
</script>
and in every element to hide just add style="display: none;" and edit input - add onkeyup="show('id') where id is id of element to hide e.g. #mytable
The reason it isn't working is because you are calling the javascript before the table element is rendered. There are three ways of doing this:
// Use CSS (best):
<table style="display:none;" id="mytable">...</table>
or
// Using DOM Load event (wait for all of the elements to render) (second best)
$(function() { $("table#mytable").hide(); });
or
// Put your javascript at the bottom of the page instead of the head. (not preferred)
Check out the fiddle I've created for you - http://jsfiddle.net/ggJSg/
Basically there are two problems:
You need to call $("#mytable").hide(); only when DOM is ready
Use proper event (like focus in my example) to trigger table display
you can also use onkeyup and document ready might help
$(document).ready(function() {
$("#mytable").hide();
$("#example").keyup(function (e) {
$("#mytable").show();
})
});
jfidle http://jsfiddle.net/dznej/
You need to use the .ready() function to execute the code when the DOM has finished loading. Then you should use the .change() function to display it:
$(document).ready(function () {
// Hide initially
$('#mytable').hide();
// When something changes in the input named `example` then show the table.
$("[name='example']").change(function() {
$('#mytable').show();
});
});
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 :)