trigger Jquery function after an auto focus - javascript

is it possible to trigger a function after an autofocus? I tried but when my textarea get the autofocus i need to click away then to click again on my textarea to trigger the function
my code is :
$('#test').focus();
$('#test').focus(function() {
alert('ok');
});

Try swapping the code around. You're event wasn't attached to the test element the first time you call focus()
$('#test').focus(function() {
alert('ok');
});
$('#test').focus();

This is because you are setting the trigger after you set the focus.
Rearrange your code and this will work fine.

The .focus() method has two different meanings based on the parameters it is passed.
In your first statement.
$('#test').focus();
This is setting the focus to the element with ID test.
Your second statement though
$('#test').focus(function() {
alert('ok');
});
What is happening here is jQuery is attaching an event handler to the focus event of the element. I suggest adding your event handlers when the DOM is loaded, then calling the .focus() event when required (which will trigger the alert).
$(function(){
$('#test').focus(function() {
alert('ok');
});
});

Related

JQuery: trigger() not calling related target

I have used the trigger() for checking the radio button after loading all the page content as the radio button value is coming from third party api.
I have make one option checked by default. So I used trigger() event for checking the radio button. The radio button have also it's click event.
In my code only radio button get selected but event is not firing.
my code is...
jQuery(document).ready(function($) {
jQuery("#btn_03").attr('checked', 'checked');
jQuery("#btn_03").trigger("change");
jQuery(".class input[type='radio']").live("change", function($) {
alert("clicked");
});
});
You need to assign the event handler before you trigger the event.
When you are actually triggering the event, you still haven't attached any listeners for that event. You are doing that in the next line. Thus the event change does get triggered but nothing happens on that event.
You can do it this way
jQuery(document).ready(function($) {
jQuery("#btn_03").attr('checked', 'checked');
jQuery(".class input[type='radio']").on("change", function($) {
alert("clicked");
});
jQuery("#btn_03").trigger("change");
});
Also use "on" to bind events instead of "live" as per the latest jQuery documentation
You need to trigger event after you attach event handler:
jQuery(".class input[type='radio']").on("change", function(e) {
alert("clicked");
});
jQuery("#btn_03").prop('checked', true).trigger("change");
Also use $.fn.on instead of long time ago deprecated $.fn.live. And it's better to set checked property instead of attribute.
You need to hook the change event before you actually call the change event. I've included a fiddle of the functionality you requested.
I've changed the change-event target to be the actual radio input since I did not have your html, but normally you would most likely want to use the name of the radio group to hook the event to, since those are usually coupled with a single behaviour - like so $("input[name='radioName']").change(function(){ // Change event code });
Sidenote: You can use '$' instead of of 'jQuery' to start an expression.
http://jsfiddle.net/du58fo3t/
$(document).ready(function() {
$("#btn_03").attr('checked', true); // Check radio button
// Hook change event on radio button
$("#btn_03").change(function() {
alert("clicked");
});
// Trigger change on radio button
$("#btn_03").trigger("change");
});

I can't prevent a button click event on JQuery

I have a button that clears a list, the click on this button shows a dialog that asks for validation (Yes/No). What I want is to disable the "Clear" button after clearing the list (Click on Yes). Here's my code :
$('#clearBtn').click(function() {
$('#alert5').show();
$('#bg').show();
$('#Yes').click(function(){
$('.list1').empty();
$('#clearBtn').disable(true);
$('#clearBtn').click(function(e){
e.preventDefault();
});
$(".alert").fadeOut(250);
$(".alertbg").fadeOut(250);
});
});
the preventDefault() function doesn't seem to work.
First never nest event handlers.
$('#cleatBtn').click(function () {
$('#alert5').show();
$('#bg').show();
});
$('#Yes').click(function () {
$('.list1').empty();
$('#cleatBtn').attr('disabled', true);
$(".alert").fadeOut(250);
$(".alertbg").fadeOut(250);
});
If you just want to disable then use the following syntax
$('#cleatBtn').attr('disabled', true);
Remove the innermost event completely.. That is not required.
Use on to bind the events, if you want the button to be enabled but turn off the event handler using off
One more option you have is to apply a class to the button when you press yes and execute the code only when the class is not present.
$('#cleatBtn').click(function () {
if( !$(this).hasClass('active')) {
$('#alert5').show();
$('#bg').show();
}
});
$('#Yes').click(function () {
$('.list1').empty();
$('#cleatBtn').attr('disabled', true);
$('#cleatBtn').addClass('active');
$(".alert").fadeOut(250);
$(".alertbg").fadeOut(250);
});
To disable a button, call the prop function with the argument true on it:
$('#cleatBtn').prop("disabled", true);
e.preventDefault(); is the correct way of cancelling events. Some older browsers also expect a return type of false. Which I think will cause jQuery to call preventDefault()?
Here's a good answer: What's the effect of adding 'return false' to a click event listener?
I think your structure looks a bit odd. you don't need to attach click events within a click event.
Just attach them all separately on document.ready events. At the moment they are nested, then go back to trying to cancel your event. The dom tree might be confused by the way the events are nested.
Hope that helps.

jquery trigger change event on checkbox

Is it possible to trigger change event on a checkbox using javascript/jquery?
Something like this (I run triggerChange on click of a button):
<label><input type="checkbox" id="chk"/>Label for chk</label>
<script>
function triggerChange(){
$("#chk").trigger("change");
}
</script>
When I run the above code I get this error: "trigger is not a function".
That trigger is not a function error message indicates something else is at play. According to this SO question:
What happens when a jQuery selector wasn't found?
no.good.at.coding says:
Do note however that you must ensure that selector is a jQuery object!
Otherwise, you could get an error indicating that "trigger is not a
function".
It's likely that you have forgotten jQuery?
As for your implementation, you should be fine the way you are using it. But trigger should be used to trigger event methods on elements that have already been attached via jQuery. Check out my demo:
Fiddle:
With click event: http://jsfiddle.net/fS4R5/1/
Without click event: http://jsfiddle.net/fS4R5/2/
HTML:
<label><input type="checkbox" id="chk"/>Label for chk</label>
JS:
function triggerChange(){
$("#chk").trigger("change");
}
$("#chk").change(function() {
alert("triggered!");
});
triggerChange();
In jQuery, you can usually trigger an event by calling it's eventhandler method withoud any function parameters.
For example a click handler can be assigned as such:
$('#mything').click(function(e){dostuff});
the click event in itself can be triggered by simply running:
$('#mything').click();
I suspect this can be done for every existing event in jQuery.
Be sure that Input of Type checkbox is enabled, in case is disabled trigger will not fire event
//fire event
$('#ceckBoxId').click();
$('#ceckBoxId').trigger('click');
or change checkbox checked val
$('#ceckBoxId').prop('checked', true);
$('#ceckBoxId').prop('checked', false);
I think the preferred method since 1.9.1 is 'on'. Specially if you use dynamically added checkboxes.
Say you have a div with id='divCOntent' and on it is a checkbox with id='cballaut', you could do this
$('#divcontent').on('click', '#cballaut', function (e) {
alert(this.checked);
});
use prop method.
$('#myCheck').prop('checked', true);
$('#myCheck').prop('checked', false);

Jquery. click event doesn't work after change event?

Having this sample code:
<input type="text" id="changeid">
click
<script>
$('#clickb').on("click", function(event){
alert(1);
return false;
});
$('#changeid').on("change", function(event){
alert(2);
return false;
});
</script>
When putting something into the text field and click the link immediately, only onchange event fires, but not link click event.
Why is that?
It seems that the change event is blocking the click event?
It is blocked by alert. Change alert to console.log you will find two events all fired.
The demo.
$('#clickb').on("click", function(event){
console.log(1);
return false;
});
$('#changeid').on("change", function(event){
console.log(2);
return false;
});​
When you edit the input and then click on the link the following happens on the inside
You start clicking on the 'link'. No events are generated yet (not even mousedown), because first the browser will do some cleanup work:
The input loses focus and will raise a blur event
The input raises a change event, since it raised a blur and the value changed
Your change event callback opens an alert(2)
The documents loses focus since a new window appeared
The link will never experience the click.
The solution is not to use alert (as xdazz proposed).
use this
$("#changeid").live('change', function () ...
onchange event fires only after the element is blurred. So when u type some text and click on the link first the element is blurred on the text field. The best way to handle the change event on having onkeyup event to track the changes made on the text field.

Multiple OnClick JQuery events firing

I have a page with div and a button on it. I have added onClick event to both of them. Now when I click the button on the div the onClick of the div is also being executed. Is there any way that I can avoid this?
Thank You,
Try this, pass the event as parameter to your onclick event and call
event.stopPropagation();
event.preventDefault();
Your onclick event assignment should be:
$(button).click(function(event) {
// script here
event.stopPropagation();
event.preventDefault();
});
In your click handler you might want to use "stopPropagation" for example:
$("button").click(function(e) {
// handle this event
// ...
// don't pass this event up to parent handlers
e.stopPropagation();
} );
There's also a related function that you might want to read about called "preventDefault" which tells the browser not to do what it normally does automatically (e.g. submit a page when a submit button is clicked)
See also:
https://developer.mozilla.org/en/DOM/event.stopPropagation
http://api.jquery.com/event.stopPropagation/
What's the effect of adding 'return false' to a click event listener?
http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/
in the listener for the link element, you can put e.stopPropagation(), which should fix it (if you're using event bubbling).
If you aren't using jQuery, make sure you set the useCapture parameter of addEventListener() to False info - MDN; you want to be sure you know which direction your events are moving through the DOM (you want them to bubble).
You need to prevent the button onClick event from bubbling to the Div. So basically at the end of your onClick function for the button, once you have done all you logic, you need to call event.stopPropagation()
If none of the above work, try out:
$("button").click(function(e) {
e.stopImmediatePropagation();
});

Categories

Resources