I have a page with a select list (ASP.NET MVC Page)
The select list and onchange event specified like this:
<%=Html.DropDownList("CompanyID", Model.CompanySelectList, "(select company)", new { #class = "data-entry-field", #onchange = "companySelectListChanged()" })%>
The companySelectListChanged function is getting called twice?
I am using the nifty code in this question to get the caller.
both times the caller is the onchange event, however if i look at the callers caller using:
arguments.callee.caller.caller
the first call returns some system code as the caller (i presume) and the second call returns undefined.
I am checking for undefined to only react once to onchange, but this doesnt seem ideal, whcy would onchange be called twice?
UPDATE:
ok, found the culprit! ...apart from me :-) but the issue of calling the companySelectListChanged function twice still stands.
The onchange event is set directly on the select as mentioned. This calls the companySelectListChanged function.
..notice the 'data-entry-field' class, now in a separate linked javascript file a change event on all fields with this class is bound to a function that changes the colour of the save button. This means there is two events on the onchange, but the companySelectListChanged is called twice?
The additional binding is set as follows:
$('.data-entry-field').bind('keypress keyup change', function (e) { highLightSaveButtons(); });
Assuming its possible to have 2 change events on the select list, its would assume that setting keypress & keyup events may be breaking something?
Any ideas?
ANOTHER UPDATE:
The select element looks fine and all works if I remove the additional 'change' binding. when the 'change' binding is added that event fires once and the hard-wired 'onchange' is fired twice.
If both events are bound via jQuery all works ok, it seems that mixing hard-wired onchange and jquery bound change events cannot be mixed? I guess this answers my question but seems like an issue with IE and binding these events with jquery.
I agree with your assessment. I've updated my small example at http://gutfullofbeer.net/onchange.html to include a jQuery handler in addition to the DOM 0 handler (the one set with the "onchange" attribute). It appears to be a jQuery bug, or at least a failure of jQuery to deal with the IE weirdness.
I logged jQuery ticket 6593.
I also encountered this issue when using IE8 and made some changes to fix this.
Instead of specifying the onchange event on the dropdownlist, I used the jquery.change() event.
Markup:
#Html.DropDownList("drpList", myList, new { #class = "myClass", id = "drpList" })
Script:
$(function () {
$('#drpList').change(function () {
.... your functionality
});
});
This works for me.. Hopes this help.
Related
Note: Not using jQuery, before you mark this as a duplicate make sure other Q/A is pure JS.
I set my event listener like this, which works perfectly when triggered via html:
document.getElementById('activitySelector').addEventListener('change', function() {
console.log("I work triggered by html but not js")
}
I'm adding additional functionality where I change the select value via javascript, which works in that the html updates, but the eventListener is never triggered:
document.getElementById("activitySelector").value = interactiveType
To achieve what you want you should create the event manually and dispatch it. It's not difficult, as you could see here: http://www.2ality.com/2013/06/triggering-events.html?m=1
This is my initial solution. Just have the event handler trigger your code wrapped as a function. That way you can just call that same function when updating via javascript.
As #dfsq has pointed out this is just how it works. Manually triggering the event would probably take more code than this method:
// All code originally in eventListener now in function
function onActivityChange() {
console.log("I work triggered by html and js")
}
// Call above function from eventlistener
document.getElementById('activitySelector').addEventListener('change', onActivityChange)
// Trigger same function after updating value
document.getElementById("activitySelector").value = interactiveType
onActivityChange()
I have an APEX application where there are many drop down items. I've bound change event handlers to them using the bind function of jQuery.
Now when I load the content of a drop-down programmatically using $('#ELEMENT').trigger('apexrefresh'), the drop-down reloads but the change event handler fires automatically.
How do I prevent this from happening? I tried avoiding binding the event handler using bind and instead adding the onChange attribute to the element. The incorrect behaviour was still present.
Here is the skeletal code:
$(document).ready(function()
{
$('#P7021_MSG_DEF').bind('change', function(e)
{
console.log('bound function onChange() msg_def');
updateStartWord();
}
);
});
function updateMsgDef()
{
console.log('function updateMsgDef() ');
$('#P7021_MSG_DEF').one('apexafterrefresh', function()
{
if( $x('P7021_RESTORE_CHK').value == 'Y')
{
setdefault('P7021_MSG_DEF', vJson.msg_def);
}
updateStartWord();
}
).trigger('apexrefresh');
}
In the above code, when the updateMsgDef is called from another function the function updateStartWord() gets called twice - once by updateMsgDef() itself and again by the onChange handler that was bound to P7021_MSG_DEF item.
If anyone could help on this?
Calling $('#ELEMENT').trigger('apexrefresh') is going to trigger the change event. Short of going back to the drawing board altogether, the solution is going to be a hack whatever you do. You could poke about in (and quite possibly break) Oracle's javascript. You could write your own AJAX to populate the select list.
The easiest way might be to check in your onChange event which element currently has focus, eg:
onChange = "if($( document.activeElement).attr('id')=='YOUR_PAGE_ELEMENT')
{ $( document.activeElement).trigger('apexrefresh'); };"
If the user has changed the select list, it should still have focus. There's no guarantee that will work in all browsers, but I think it should be ok in current Chrome and IE versions.
I've been in a similar situation to yours, and have come to accept that if the page logic is too complicated to implement using DAs, maintaining it is likely going to be a nightmare whatever happens. Much as I like "proper" programming, Apex is really all about the declarative controls.
I wrote a Chrome Extension that automatically fills some registration forms. There are some select fields that need to be triggered on "change" event in order to start some Ajax calls.
First I use JQuery attr or val to change the value of the select field, and than I use .trigger to invoke the "change" event, but this last one doesn't work.
Example:
I want to select the option that contains the word "London" and invoke
the change element in order to start some operations of the native
code that have some listeners on "change" event
jQuery("#SelectElement option:contains('London')").attr("selected", "selected");
jQuery("#SelectElement").trigger("change"); <--- not works
I tried also:
jQuery("#SelectElement option:containt('London')").attr("selected", "selected").change();
But if I try this code on console, it works.
Suggestions?
I had the same problem and as far as I know it's because of something called framework event listeners. that you cannot trigger from your code by jquery! but the solution is trigger the event this way:
$(selector)[0].dispatchEvent(new Event("eventName"))
In my case,
var event = new CustomEvent('change');
did not work.
I had to initialize the event like this:
var evt = document.createEvent("HTMLEvents");
evt.initEvent("keyup", true, true);
First arg 'bubbles' should be true so the event should bubble up through the event chain.
event.initEvent(type, bubbles, cancelable);
Source:
https://developer.mozilla.org/en-US/docs/Web/API/Event/initEvent
I have a fairly large javascript class that generates an complete ajax-generated application. In one version of the ajax page there are a number of dropdown menus. These menus can get created and destroyed at various points during the life cycle of the application.
This is the behaviour I see:
User opens page version 1: no dropdowns
User goes to page version 2: dropdowns added with jQuery onchange event. Work as intended.
User returns to version 1 of page, dropdowns removed.
User returns to version 2 of page, dropdowns added again (using same element IDs)
dropdowns will now have 'double' event handling, triggering the event for each onchange.
The behaviour I'm struggling with is as follows.
On the initial page load, I add an onchange event:
function myClass(){
//Initiate once for current and future elements.
jQuery(document).on('change',".mydropdowns",
function(e){
self.submitDescriptionChange(this);
}
);
}
myClass.prototype.submitDescriptionChange = function (el){
doSomeAjaxStuff();
}
This works fine, except that each time the user goes to pages version 1 and returns to page version 2, the event gets multiplied. Very quickly you can end up with the event firing 20 times per change event, which in this case creates 20 ajax calls.
Logically, by using jQuery.off() I should be able to avoid this. But what happens instead is that the event is removed from both past and future elements, which means that when I recreate page version 2, the dropdowns won't work.
Every way I have tried this (and I've tried LOADS), I either end up with no event firing, or multiple events firing. I cannot seem to find a way to add/replace the elements whereby the event is only ever fired once.
Any ideas how I can solve this?
UPDATED
Yeah, so it turns out I misdiagnosed the problem. It actually came from repeatedly rebinding a 'hashchange' event, rather than rebinding the onchange event. Apologies for misdirection. Moving to bind() function to somewhere where it only executed once fixed the issue.
Since you do not want .off() to remove your events from other pages, I would suggest using namespaces for your events. For example, something like this:
function myClass(pageno) {
var pref_ev = 'mypage' + pageno + '.' + 'change';
$(document).off(pref_ev).on(pref_ev, ".mydropdowns", function(e) {
self.submitDescriptionChange(this);
});
}
This way, each page will have its own "change" event such as "mypage1.change". The event is still registered normally as a change event; the prefix namespace "mypage1" is used to only perform the .off() call on the right events.
I am not sure what plugin you are using for your dropdown menus but there should be a "destroy" method on that plugin. If you call that when removing the dropdowns that should work. Also, if you are only hiding the second page and not actually removing it from the DOM you dont have to re-invoke the plugin as the plugin will still be saved on the element.
I'm really stuck with a jQuery issue and I hope someone can help me out...
So I have a list of options on the left, and when you click on one, a form is generated via Ajax on the right. There's this element in the form:
<input type="text" class="value" value="something">
And what I want to do is to call
$(".value").tagsInput();
which is a jQuery plugin that works pretty much like Stack Overflow's 'Tags' input field when you ask a question.
So I tried this:
$(document).ready(function() {
$(".value").on("load", function () {
console.log("Tags Input");
$(".value").tagsInput();
});
});
and nothing is printed out. I've also tried this:
$(document).on("change", ".value", function () {
console.log("Tags Input");
$(".value").tagsInput();
});
and it doesn't work either. I'm wondering where I did wrong. Can anyone help me out?
As pointed out by Shabnam, the "change" event is not what you want, as it is fired only once the field is blurred.
Anyways, from the plugin documentation, it looks like you don't have to call that function every time a key is pressed, but it attaches its own event handlers autonomously.
So, probably you should be fine with just:
$(document).ready(function() {
$(".value").tagsInput();
});
Your .on handler will never work, as the load event is fired only by document when the page is ready.
If you want to debug things a bit, have a look at the supported callbacks, such as onChange.
SIDE NOTE
I don't like how that plugin is written, as it clogs the "global" jQuery.fn namespace with lots of functions, while jQuery documentation recommends not doing so (see: Namespacing).
UPDATE
See here: http://jsfiddle.net/aFPHL/ an example of this working (the .load() was monkeypatched to avoid having to call an actual URL, but its behavior is pretty much the same as the real one).
"change" event gets fired when the input element loses focus. If you want ajax call at the end of each key input, try using keyboard events