In my application, I have this code:
postCreate: function(){
// ...
// Change the listWidget's order depending on whether the checkbox is
// ticked or not
self.extraWidget.orderByNameWidget.on( 'click', function( e ){
var orderByNameWidget = this;
field = orderByNameWidget.get('value') ? 'firstName' : 'lastName';
// Make up the collection with the initial filters
var collection = self.store;
if( self.initialFilter ) collection = collection.filter( self.initialFilter );
collection = collection.sort( field );
self.listWidget.set('collection', collection);
});
This code is there so that the user can click on a checkbox (orderByNameWidget), and change the sorting of contacts.
orderByNameWidget is a normal Dojo CheckBox.
Now, I have a global setting of what that value should be to start with. The neater way to deal with it would be setting the value of the checkbox, and then trigger the event:
// Artificially emit the initial click if the default says so
if( ConfigVars.workspacesUsersInfo.orderByNameDefault ){
self.extraWidget.orderByNameWidget.set( 'value', true );
self.extraWidget.orderByNameWidget.emit( 'click', { bubbles: true, cancelable: true });
}
While the first line works (setting the widget), the second one doesn't -- the 'click' event is never actually triggered for the widget.
I tried every single possible combination, emitting this event on the domNode etc. -- but no, it doesn't seem to want to do anything.
In Button.html, the basis for CheckBox, Dojo has:
data-dojo-attach-event="ondijitclick:__onClick"
I wonder if that's the problem. So... what should I write for a full simulation of the checkbox click? Any pointers?
Is there a reason why you can't use the change event instead of click to begin with? That ought to fire on both user clicks and programmatic changes. (And keyboard events, for that matter, which click likely won't fire on.)
Related
I basically want to know when the user has clicked the checkbox. If checkbox is clicked then I want the div to output a msg and once checkbox is not checked then output another msg but user has to check first. The checkbox gets created dynamically. But somehow I dont know what the value is.
There are 2 problems:
When checkbox is clicked, the check mark does not stay
If checkbox is clicked, a value does not output on the div
Here is a example:
http://jsfiddle.net/8GjdS/103/
Code:
var myView = Backbone.View.extend({
events: {
'click #check': 'checkboxHandler'
},
initialize: function() {
_.bindAll(this, 'checkboxHandler');
},
checkboxHandler: function(e) {
var filter = $('#check').is(':checked');
console.log(filter);
$('#out').append(filter);
return false;
},
});
var v = new myView({el: '#view-goes-here'});
v.render();
$('#view-goes-here').append('<div class=divs" align="right"><input id="check" type="checkbox" value=""><font size="4">check</font></input></div>');
There are a couple of issues.
First: When you return false from an event handler (or trigger event.preventDefault() you stop the event from bubbling up. That means, you handle the event yourself and it will never trigger the usual action -- in this case, it means the checkbox will never change. You should return true instead, in your checkbox handler.
Second: The value is not appended to your out div because you call the append function with a boolean as the argument. The easiest way in this case is probably to "cast" it to a string like so:
$('#out').append('' + filter);
Third: While it's a workable approach to listen for the click event, it could be argued that it's more correct to listen for the change event instead. From MDN:
The change event is fired for <input>, <select>, and <textarea> elements when a change to the element's value is committed by the user.
Here is an updated fiddle: http://jsfiddle.net/jzvzgdp4/
I have following jquery code, where on click of a check box I will show a popup value.
Except in IE,in all other browser it works as expected. That is, on change the check box will be checked and the popup will be opened.
However in IE8 its not getting checked, however popup is displayed properly.
Code :
$('#TAndC').change(function(){
if( $('input[name="TAndC"]').is(':checked'))
{
$('#TandCBox').show();
var termsandcondition = GetEnum().TermsandConditionsPageId;
var actionURL = '#Url.Action("ShowTAndC", "Account", new { isFromCheckBox = true })';
$('.popUpForm').load(actionURL);
var msgBox = $('#terms').attr('href');
MaskMsgPopUp(msgBox);
return false;
}
});
If your element is a checkbox and not a dropdown then use click anyway.
If your selector is referring to a dropdown use click if you need to support IE8 and older.
See why that is below.
According to the MSDN for change/onchange, the event is not triggered until the change is committed.
In addition the event is also not triggered when the value is changed programmatically.
To quote:
This event is fired when the contents are committed and not while the
value is changing. For example, on a text box, this event is not fired
while the user is typing, but rather when the user commits the change
by leaving the text box that has focus. In addition, this event is
executed before the code specified by onblur when the control is also
losing the focus. The onchange event does not fire when the selected
option of the select object is changed programmatically. Changed text
selection is committed.
To invoke this event, do one of the following:
Choose a different option in a select object using mouse or keyboard navigation.
Alter text in the text area and then navigate out of the object.
If you must support IE8 and older, you are probably better of to use the click event instead which get's triggered when you release the mouse and your new choice is selected.
instead of .change use below code and try
$(document).ready(function(){
$(document).on('click','#TAndC',click_function){
if( $('input[name="TAndC"]').is(':checked'))
{
$('#TandCBox').show();
var termsandcondition = GetEnum().TermsandConditionsPageId;
var actionURL = '#Url.Action("ShowTAndC", "Account", new { isFromCheckBox = true })';
$('.popUpForm').load(actionURL);
var msgBox = $('#terms').attr('href');
MaskMsgPopUp(msgBox);
return false;
}
});
});
Right now I have this:
Event.observe(
'hidden',
'keydown',
itemOptions["_something"].showButtonsForThat
);
whereas showButtonsForThat is showButtonsForThat : function(){....function body....}.
But I needed to add other event handlers:
Event.observe(
'inputF',
'keydown',
function() { document.getElementById('hidden').value = document.getElementById('inputF').value; }
);
Event.observe(
'inputF',
'blur',
function() { document.getElementById('hidden').value = document.getElementById('inputF').value; }
);
which will change the value of the hidden field every time I change something in the input field. And now I want the first event handler (about the hidden element) to trigger whenever its value is changed (which changes according to whatever is in the input field..
I tried with eventName 'change' but unsuccessful. Somehow using onchange="myFoo();" in the html element + jQuery, etc., didn't work. Maybe my syntax misplacement mistake, but I tried many things and following different examples.
Clarification: I want to observe the change of hidden, because it will change automatically when I type something different in inputF. So I basically will NOT interact with hidden at all.
If none of the traditional ways worked for you, you could simply use a work-around, as bellow:
Event.observe(
'inputF',
'keyup',
itemOptions["_something"].showButtonsForThat
);
This means that you will still observe the inputF field, but will call your needed function on that. Anyway, you will call the handler on change of hidden, which on the other hand changes along with inputF, meaning that changing either of the fields happens at the same time and for the same purpose.
P.S. Better use keyup event name (as in my example), because keydown requires one more click, for the last symbol to be updated. I.e., if you type asde in inputF, then you will have asd in hidden, unless you click once more with the keyboard. And with keyup you won't have this problem.
var h = document.getElementById('hidden'),
f = function() { h.value = this.value; };
Event.observe('inputF','keydown', f);
Event.observe('inputF','blur', f);
...
In jqGrid, Is there a "built-in" way to know what mouse button was clicked, before row selection?
Currently we have jqGrid with some actions bind on "onSelectRow" event of jqGrid. The problem is that when user right click on that row, onSelectRow event raised to and action performed. What I need, is to ignore "onSelectRow" when user right click on a row.
EDIT: I know there exists onRightClickRow event, but it raised after onSelectRow and action already performed.
I found that I can know what button clicked by "type" of event object. When it's click, the type is "click" when it's right click, the type is "contextmenu"....Does exists the additional way, or I must check type to know what button is clicked?
Thanks
It's good question! The reason of such behavior is the following. jqGrid register an event handler for the event contextmenu on the whole grid <table> element with the following code (see here)
.bind('contextmenu', function(e) {
td = e.target;
ptr = $(td,ts.rows).closest("tr.jqgrow");
if($(ptr).length === 0 ){return;}
if(!ts.p.multiselect) { $(ts).jqGrid("setSelection",ptr[0].id,true,e); }
ri = ptr[0].rowIndex;
ci = $.jgrid.getCellIndex(td);
$(ts).triggerHandler("jqGridRightClickRow", [$(ptr).attr("id"),ri,ci,e]);
if ($.isFunction(this.p.onRightClickRow)) {
ts.p.onRightClickRow.call(ts,$(ptr).attr("id"),ri,ci, e);
}
});
How one can see from the code it calls setSelection method and calls onRightClickRow callback and trigger jqGridRightClickRow event. So if you don't need the selection of rows and if you don't use onRightClickRow and jqGridRightClickRow you can just unbind the event handler:
$("#list").unbind("contextmenu");
If you do want use onRightClickRow callback or if you don't sure whether you need to use jqGridRightClickRow somewhere you can "subclass" the event handler. The implementation is depend a little from the version of jQuery which you use. Starting with jQuery 1.8 one should use a little another call to get the current events registered on the DOM element. The corresponding code could be about the following:
//$grid.unbind('contextmenu');
var getEvents = $._data($grid[0], "events"); // $grid.data("events") in jQuery ver<1.8
if (getEvents && getEvents.contextmenu && getEvents.contextmenu.length === 1) {
var orgContextmenu = getEvents.contextmenu[0].handler;
$grid.unbind('contextmenu', orgContextmenu);
$grid.bind('contextmenu', function(e) {
var oldmultiselect = this.p.multiselect, result;
this.p.multiselect = true; // set multiselect to prevent selection
result = orgContextmenu.call(this, e);
this.p.multiselect = oldmultiselect; // restore multiselect
return result;
});
}
The demo demonstrate the above code live.
Events are listed here: http://www.trirand.com/jqgridwiki/doku.php?id=wiki:events
There is an onRightClickRow event.
Also, using the plain jquery event object and which will tell you. http://api.jquery.com/event.which/
You must use 3rd parameter to onRowSelected and which or the type like you mentioned.
I have a pretty simple form. When the user types in an input field, I want to update what they've typed somewhere else on the page. This all works fine. I've bound the update to the keyup, change and click events.
The only problem is if you select an input from the browser's autocomplete box, it does not update. Is there any event that triggers when you select from autocomplete (it's apparently neither change nor click). Note that if you select from the autocomplete box and the blur the input field, the update will be triggered. I would like for it to be triggered as soon as the autocomplete .
See: http://jsfiddle.net/pYKKp/ (hopefully you have filled out a lot of forms in the past with an input named "email").
HTML:
<input name="email" />
<div id="whatever"><whatever></div>
CSS:
div {
float: right;
}
Script:
$("input").on('keyup change click', function () {
var v = $(this).val();
if (v) {
$("#whatever").text(v);
}
else {
$("#whatever").text('<whatever>');
}
});
I recommending using monitorEvents. It's a function provide by the javascript console in both web inspector and firebug that prints out all events that are generated by an element. Here's an example of how you'd use it:
monitorEvents($("input")[0]);
In your case, both Firefox and Opera generate an input event when the user selects an item from the autocomplete drop down. In IE7-8 a change event is produced after the user changes focus. The latest Chrome does generate a similar event.
A detailed browser compatibility chart can be found here:
https://developer.mozilla.org/en-US/docs/Web/Events/input
Here is an awesome solution.
$('html').bind('input', function() {
alert('test');
});
I tested with Chrome and Firefox and it will also work for other browsers.
I have tried a lot of events with many elements but only this is triggered when you select from autocomplete.
Hope it will save some one's time.
Add "blur". works in all browsers!
$("input").on('blur keyup change click', function () {
As Xavi explained, there's no a solution 100% cross-browser for that, so I created a trick on my own for that (5 steps to go on):
1. I need a couple of new arrays:
window.timeouts = new Array();
window.memo_values = new Array();
2. on focus on the input text I want to trigger (in your case "email", in my example "name") I set an Interval, for example using jQuery (not needed thought):
jQuery('#name').focus(function ()
{
var id = jQuery(this).attr('id');
window.timeouts[id] = setInterval('onChangeValue.call(document.getElementById("'+ id +'"), doSomething)', 500);
});
3. on blur I remove the interval: (always using jQuery not needed thought), and I verify if the value changed
jQuery('#name').blur(function ()
{
var id = jQuery(this).attr('id');
onChangeValue.call(document.getElementById(id), doSomething);
clearInterval(window.timeouts[id]);
delete window.timeouts[id];
});
4. Now, the main function which check changes is the following
function onChangeValue(callback)
{
if (window.memo_values[this.id] != this.value)
{
window.memo_values[this.id] = this.value;
if (callback instanceof Function)
{
callback.call(this);
}
else
{
eval( callback );
}
}
}
Important note: you can use "this" inside the above function, referring to your triggered input HTML element. An id must be specified in order to that function to work, and you can pass a function, or a function name or a string of command as a callback.
5. Finally you can do something when the input value is changed, even when a value is selected from a autocomplete dropdown list
function doSomething()
{
alert('got you! '+this.value);
}
Important note: again you use "this" inside the above function referring to the your triggered input HTML element.
WORKING FIDDLE!!!
I know it sounds complicated, but it isn't.
I prepared a working fiddle for you, the input to change is named "name" so if you ever entered your name in an online form you might have an autocomplete dropdown list of your browser to test.
Detecting autocomplete on form input with jQuery OR JAVASCRIPT
Using: Event input. To select (input or textarea) value suggestions
FOR EXAMPLE FOR JQUERY:
$(input).on('input', function() {
alert("Number selected ");
});
FOR EXAMPLE FOR JAVASCRIPT:
<input type="text" onInput="affiche(document.getElementById('something').text)" name="Somthing" />
This start ajax query ...
The only sure way is to use an interval.
Luca's answer is too complicated for me, so I created my own short version which hopefully will help someone (maybe even me from the future):
$input.on( 'focus', function(){
var intervalDuration = 1000, // ms
interval = setInterval( function(){
// do your tests here
// ..................
// when element loses focus, we stop checking:
if( ! $input.is( ':focus' ) ) clearInterval( interval );
}, intervalDuration );
} );
Tested on Chrome, Mozilla and even IE.
I've realised via monitorEvents that at least in Chrome the keyup event is fired before the autocomplete input event. On a normal keyboard input the sequence is keydown input keyup, so after the input.
What i did is then:
let myFun = ()=>{ ..do Something };
input.addEventListener('change', myFun );
//fallback in case change is not fired on autocomplete
let _k = null;
input.addEventListener( 'keydown', (e)=>_k=e.type );
input.addEventListener( 'keyup', (e)=>_k=e.type );
input.addEventListener( 'input', (e)=>{ if(_k === 'keyup') myFun();})
Needs to be checked with other browser, but that might be a way without intervals.
I don't think you need an event for this: this happens only once, and there is no good browser-wide support for this, as shown by #xavi 's answer.
Just add a function after loading the body that checks the fields once for any changes in the default value, or if it's just a matter of copying a certain value to another place, just copy it to make sure it is initialized properly.