Trigger working only after alert inside document ready - javascript

I have this code:
$(document).ready(function () {
active_menu('mn_tours');
$('#buscar').val(localStorage.getItem("busqueda"));
$('#btbuscar').trigger('click');
});
I want to trigger the submit event on that button right away when page loads, but it doesn't seem to work, but when I put this:
$(document).ready(function () {
active_menu('mn_tours');
$('#buscar').val(localStorage.getItem("busqueda"));
alert('Something');
$('#btbuscar').trigger('click');
});
It actually works, but I don't know how to correct this.

With preliminary testing, this code works...
<form id="myForm" action="#" method="POST">
<input type="text" id="buscar"/>
</form>
<div id="btbuscar">
help
</div>
$(document).ready(function () {
$('#buscar').val(localStorage.getItem("busqueda"));
$("#btbuscar").bind('click', function(evt){
$("#myForm").submit()
})
$("#myForm").bind('submit', function(evt){
alert("form submitted")
})
$('#btbuscar').trigger('click');
});
without seeing your original button listener assignments, I can't tell if this is exactly what you want, but provided the listeners are set properly, this method will work.

You have a timming problem. When javascript run this:
$('#btbuscar').trigger('click');
the HTML element doesnt exist yet, so the submit never happen.
Alert will pause the javascript execution. So when you click OK, the HTML element #btbuscar is already loaded on page and the submit work.
It's not safe, but you can use setTimeout
$(document).ready(function () {
active_menu('mn_tours');
setTimeout(function(){
$('#buscar').val(localStorage.getItem("busqueda"));
$('#btbuscar').trigger('click');
},1000);
});

Related

jQuery trigger on page load

How can I make jQuery run when my webpage has finished loading?
This is not what I want. All that this does is wait for the page to finish loading before any Javascript CAN be run.
$(document).ready(function(){
//Code here
});
What I want is for this to run when the page loads. I don't want it to wait for 'click' or 'change'. Can I add a 'load' or something to this?
$(document).on("change", "#input", function(e) {
$("#output").val($(this).val());
});
A workaround I have been using is to use jQuery to "change" the selected option on a select box, thereby triggering the code I actually want to run.
I have seen a bunch of questions like this, but every time the answer just says to use $(document).ready(function(){//Code}); which is not what I'm looking for.
Any ideas?
EDIT: Here is a better example of what I'm looking for.
This code below will run when the element with the id of 'input' is clicked. That is the only time it will run. I would like for it to run as soon as it is ready - as soon as $(document).ready(function(){}); can run it.
$(document).ready(function(){
$(document).on("change", "#input", function(e) {
$("#output").val($(this).val());
});
});
I think that this would work, but I was hoping for a nicer solution and one that doesn't require me to rewrite everything as functions.
$(document).ready(function(){
function runWhenReady(){
$("#output").val($(#input).val());
}
$(document).on("change", "#input", function(e) {
runWhenReady();
});
runWhenReady();
});
I think that this will run runWhenReady() when #input is clicked, and when the page finishes loading. My question is, is there a simpler way to do this?
I think the only way to do what I want is to name the function and call it two different ways.
$(document).ready(function(){
function xyzzy(){
$("#output").val($(#input).val());
}
//Call the function when #input is clicked
$(document).on("change", "#input", function(e) {
xyzzy();
});
//Call the function when the page loads
xyzzy();
});
This will call the function when the page has finished loading, as well whenever #input is clicked.
I think you're looking for $(window).load()
$(window).load(function(e){
// code here
});
Answer to your question in the comments:
$(document).on('click', '#input', function(e){
$('#output').val($(this).val());
});
Can I add a 'load' or something to this?
yes you can which will like $(window).on( "load", handler )
Also there is not much difference between the above code and
$( window).load(function() {
// Handler for .load() called.
});
The first method is just short cut of the second one
$(document).ready happens when all the elements are present in the DOM, but not necessarily all content.
$(document).ready(function() {
alert("document is ready");
});
window.onload vs document.onload
window.onload or $(window).load()
happens after all the content resources (images, etc) have been loaded.
$(window).load(function() {
alert("window is loaded");
});
From your Example:
$(document).ready(function(){
function runWhenReady(){
$("#output").val($(#input).val());
}
$(document).on("change", "#input", function(e) {
runWhenReady();
});
runWhenReady();
});
You could write:
$("#input").on("change", function() {...});
which defines a handler for your input. Everytime you change the value in the input it will call the function passed as argument. That make the whole $(document)... unneccessary.
If you want to run the function just once, as soon as possible wrap it in a IIFE like:
(function(){...});
Here is a pretty good blog post about IIFE:
http://benalman.com/news/2010/11/immediately-invoked-function-expression/

Trigger click after load page

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();" />

jQuery event.Preventdefault(); is not doing anything

i have some scripts on my site that send replies to a server and reload the page using ajax. sometimes though, it reloads the page for no reason.
so I added this code
<script type="text/javascript">
$("form").submit(function(){
event.preventDefault();
return false;
)
</script>
but it is still reloading the page when i hit sumbit.
why.
You simply forgot to bring in the event argument into the handler:
$("form").submit(function( event ) {
Also: check the error console, in your example code you are missing an ending bracket });
As a side note: make sure you are selecting the form element after it has been loaded, to be safe use domReady:
$(function() {
$("form").submit(function(event){
event.preventDefault();
});
});
event as a global (window.event) is non-standard. jQuery normalizes this for you, so just pass in event as an argument:
$(document).ready(function() { // Make sure you wait until the document is ready
$("form").submit(function(event) {
event.preventDefault();
});
});
Also, returning false calls event.preventDefault() as well as event.stopPropagation(). You only want the first to happen, so be explicit.
$("form").submit(function(event){})
In a comment on another answer, you've said:
it still reloads the page
That suggests that you have this code above the form you want it to act on in the HTML. Move the script below the form (usually just before the closing </body> tag is best), or use jQuery's ready event.
Also note that if you're using return false, you don't need event.preventDefault, because return false from a jQuery event handler does event.preventDefault() and event.stopPropagation(), so:
<form ...>
<!-- ... -->
</form>
<!-- ... -->
<script>
$("form").submit(function(){
return false;
});
</script>
</body>
Or alternately, this anywhere on the page, using the shortcut for ready:
$(function() {
$("form").submit(function(){
return false;
});
});

JQuery onclick do something ... after click alert

I am using this code:
onclick="$('#default').click();" ... is there any way to return an alert of something if it's done sucessfully?
Update:
There seems to be a proble here:
onclick="$('#default').click( function() { alert('clicked'); });"
That syntax is a bit off. Usually you'd use jQuery's click() like this:
HTML:
<a id="something">Text</a>
JavaScript:
$('#something').click( function() { alert('clicked'); });
Update:
Even your updated code seems to work, but it is very bad code like that - you might have some error somewhere else in your javascript, or in the DOM structure. See http://jsfiddle.net/HCQeN/1/
It would be much better to seperate the jquery from the onclick, like: http://jsfiddle.net/ctUgp/
Lets say your example is:
<input type="button" id="myButton" onClick="$('#default').click()" />
What you want is:
<input type="button" id="myButton" />
<script type="text/javascript">
$(document).ready(function(){
// this code will run when the document has loaded
// and all elements are in place
$("#myButton").click(function(){
// this code will be run when the user clicks on
// the button we created above
$('#default').click(); // this calls the click event on #default
alert('Finished'); // now it is finished
}); // close the click handler on #myButton
$('#default').click(function(){
// this code will be run when the user click on
// the element with id "default" OR (in this case)
// when the click event is triggered from clicking the
// button above.
alert('#default was clicked');
}); // close the click handler on #default
}); // close the document.ready code block.
</script>
just like this
$('#default').click( function() {
alert('Handler for .click() called.');
} );
Try:
onclick="$('#default').click(function() { alert('foobar'); });"

Javascript doesn't work on ajax generated code?

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
});

Categories

Resources