jQuery 1.7.2 and IE7 on() doesn't seem to fire for selects - internet-explorer-7

I have a table of rows where are dynamically added, but for some reason the on() event doesn't seem to fire when I change the value of a select.
For simplicity, I wrote the following jsFiddle. This is a VERY simplistic example of what I am doing. I do have to note that I was unable to verify if the jsFiddle failed the same way in IE7 because jsFiddle does not seem to work in IE7 at all.
The basics of my code are this...
First, the page loads with 1 or more of these rows, which represent a complex "subform" to be posted to Spring MVC. The subform has a group of 5 SELECT tags that have an event handler attached at the top TABLE as such:
$('#parentTable').on('change', 'div.additional div[class^="additional"] select', function() {
// ...enable/disable siblings according to value
}
At the bottom of the table is an Add button. When the user clicks it, I take the last visible row, clone it, use regex to fix the index on the name/id, and set all the fields blank and disables except one field, which is used to do a lookup. This all has the appearance of working.
The user enters a value in the lookup field, clicks Lookup, which performs an AJAX call, filling in the subform then calling the change on the selects to set their default state like so:
$subTable.find(':input:not(:button)').change();
This fires the above on() as expected. However, if I physically click on the resulting SELECTs and change their values the on() event handler is not called.
I have verified that the resulting cloned table row looks/smells/feels correct, at least from using IE8's Developer Tools (I have IE8 in IE7 compatibility mode for testing, because IE7 has VERY limited testing and the problem seems to be present there too). When I run this in Chrome it works perfectly fine, however I am aware the clone is technically working differently.
Any help would be appreciated.
Update
I tried swapping the selector to drop the class attr as suggested below:
$('#parentTable').on('change', 'div.additional div select', function() {
// ...enable/disable siblings according to value
}
And I tried all caps like the referenced post:
$('#parentTable').on('change', 'div.additional div[class^="ADDITIONAL"] select', function() {
// ...enable/disable siblings according to value
}
The first worked the same way, the second did nothing at all (disabled all on() change handling).
Will continue to play with this until I get it working. There has to be something simple going wrong here.
Update 2
I tried adding a class to all the `SELECT`s, and added the following two:
$('select.addedClass').on('change', function() {
alert("Select change:" + $(this).val());
});
$('#parentTable').on('change', 'select.addedClass', function() {
alert("Select change 2:" + $(this).val());
});
Here is the process I performed:
Reloaded page, both alerts fire for the single row there
Added a row
Performed AJAX lookup, which calls $addedTable.find(':input:not(:button)').change(); as described above, both events fire
Change the value of one of the selects, neither alert fires.
I would expect the first to fail, since the event listener is connected directly to the SELECT and not a higher level parent, but the second one fails the same way. So, in the Developer Tools, I tried to run the following:
$('#order.itemList1.additionalLine1').change()
Which is the ID of one of the selects I added, and still nothing fired. It's as if the event handler is ignoring all added SELECTs.
To make sure the select was working on the on(), I did this in the console after I added the new row:
$('#parentTable').find('div.additional div[class^="additional"] select').each(function() {
alert($(this).attr('name') + '(' + $(this).prop('id') + ')' + ' : ' + $(this).val());
});
Update 3
I ended up putting in a horrible hack that, for IE7 only, drops and re-adds the change handler directly on the SELECTs. It's ugly, but I have to support IE7, so...
I am leaving this open to see if anyone has a better solution, or might know why it's not working.

The problem isn't the change event, or the delegation on select elements.
It's the attribute selector:
div[class^="additional"]
IE7 and below don't do attribute selectors.
I've done a bit of searching and a few people seem to think this can be solved using case-specific syntax.

Related

How do I return focus to an element when the entire page changes?

I have a complicated setup. My application is driven by a set of "rules" which dictate what the user interface is. The UI is rendered by looping through the rules and creating the individual dropdowns. Initially, everything renders properly. However, once a user makes a change to the UI, other rules may be affected. In my application, an api call is made, which then returns a modified set of rules. In the attached plunker, I've simplified things such that only the new set of rules is applied, which causes the page to re-render. The problem is that my users would like to be able to tab between all of the entries on the page and make changes. However, once the page is re-rendered, the currently selected page element is now gone nothing has the focus. I've tried to put the focus back on the proper element by tracking a common Id, but to no avail.
Using either of these doesn't seem to work.
var el = document.getElementById(focusId);
el.focus();
angular.element(el).focus();
I've also tried using the autofocus attribute on the dropdown that I want to have focus, but that didn't work either. I'm using angularjs 1.2. Any ideas are appreciated.
http://plnkr.co/edit/ND9PKqULIOlixWR4XChN?p=preview
If you want to assign auto focus dynamically to a element on the DOM from angular you can use this:
var myEl = angular.element(document.querySelector('select'));
myEl.attr('autofocus',"attr val");
You can also pass in an id like: angular.element(document.querySelector('#focusId'));
You can look here for a prior answer which may be of some more help!
-Cheers!
Problem here is, you are trying to focus the element before the blur event completes. So you need to execute the focus code after blur event. Async execution of your focus code would solve the problem. You can use either setTimeout or $timeout.
setTimeout(function(){
angular.element('#'+focusId).focus();
/* //or
var el = document.getElementById(focusId);
el.focus();
*/
});
or
$timeout(function(){
angular.element('#'+focusId).focus();
/* //or
var el = document.getElementById(focusId);
el.focus();
*/
});
dont forgot to inject $timeout to your controller if you are using second code. Hope this helps :)

Whats the equivalent for ng-grid's "beforeSelectionChange" in ui-grid?

In ng-grid, I used to use beforeSelectionChange in the following way:
When the user selects a row, an ajax call is performed. While the ajax call is happenning I set $scope.doingAjaxCall = true, and to prevent the user from changing the selection, I had this in the grid definition:
beforeSelectionChange: function () {
return !($scope.doingAjaxCall);
},
which locks/freezes the selection if the ajax call is happenning.
Now, in ui-grid (aka ng-grid 3), I don't know whats the equivalent for afterSelectionChange.
In this section of the documentation:
http://ui-grid.info/docs/#/api/ui.grid.selection.api:PublicApi
I see two events:
rowSelectionChanges
rowSelectionChangedBatch.
These seem to be the equivalent of the old afterSelectionChange
And in this section of the documentation:
http://ui-grid.info/docs/#/api/ui.grid.selection.service:uiGridSelectionService
I see these two methods that seem to be related to the need:
raiseSelectionEvent(grid, changedRows, event)
decideRaiseSelectionEvent(grid, row, changedRows, event)
But I don't understand how to use them
Important note:
I'm using multiSelect: false (ie: only one row can be selected)
This is a bit of a hack, but it'll get the job done until you find a better solution. Here's a working plunker.
I assume you use rowSelectionChanged to perform the AJAX call and toggle doingAjaxCall.
gridApi.selection.on.rowSelectionChanged($scope, function(row) {
$log.log('Row ' + row.entity.id + ' selected: ' + row.isSelected);
$log.log(' Simulating ajax call...');
$scope.doingAjaxCall = true;
$timeout(function() {
$log.log(' ...done with ajax call');
$scope.doingAjaxCall = false;
}, 2000);
});
Then, modify the template that ui-grid uses for the select buttons.
$templateCache.put('ui-grid/selectionRowHeaderButtons',
'<div ' +
' class="ui-grid-selection-row-header-buttons ui-grid-icon-ok" ' +
' ng-class="{\'ui-grid-row-selected\': row.isSelected}" ' +
' ng-click="grid.appScope.clickConditions() && selectButtonClick(row, $event)"> ' + // Modified template here
' ' +
'</div>'
);
This way, $scope.clickConditions() is evaluated before the actual click logic is called. If it's falsy, then selectButtonClick, which handles the internal selection logic, is never called.
$scope.clickConditions = function() {
// Check for any other conditions you need
return !$scope.doingAjaxCall;
};
As I mentioned, this is very hacky! There are better ways to overwrite the templates (e.g. ui-grid/selectionRowHeaderButtons), when overwriting templates you'll have to check the logic when updating, you should probably let the user know that something is happening visually when the AJAX call is performed, etc.
A better solution would be to fork the repo and add your own beforeSelectionChange logic (probably starting here). But it seems like you haven't gotten much help elsewhere, so hope the this gets you started at least!
ui-grid provides the tools to do this, I'm not sure there's a "ui-grid" way, but there are definitely ways to do it that are compatible.
Based on your description I'm assuming you are only allowing single selection, because if you allowed multiple selection they could keep adding selections and you'd run the ajax in the background. So I assume you're setting multiSelect: false per http://ui-grid.info/docs/#/tutorial/210_selection
I can see two ways to get the result:
If the user tries to select a row whilst an ajax call is running, set the selection back to where it was. This means you'd have to listen to the selectionChanged and selectionChangedBatch events, keep track of the selection that you want, and keep track of when an ajax call was in progress.
Use an isRowSelectable function that doesn't let any row be selected if an ajax call is running. The function itself is similar to what you used to have with ng-grid i.e. return !$scope.doingAjaxCall. The difference is you need to call notifyDataChange whenever you change the value of $scope.doingAjaxCall. From memory making a row not selectable by the user will still allow it to be selected in code - so this won't change that the row is selected.
I'd probably go with the second option.
Adding information as requested: isRowSelectable is in the tutorial as noted above (there's an example of it working). The only trick is that I have a feeling it's only re-evaluated on specific events, so it may not just automatically remove the select from each item when you change the doingAjaxCall variable. Hence I recommended calling notifyDataChange, which is also in the tutorial.
I'd suggest you have a go at it in a plunker, and then if you have difficulty I can look and provide advice. I don't have the time right now to write it from scratch.

angular event doesn't update page

I'm converting a page in a mvc application with a lot of inline jquery javascript to angular using typescript.
The first calls works fine but I have a problem: based on a selection in a dropdown, the event updates several controls in the view, make a few ajax calls and finally update the view with the data from the calls.
Seems the conversion is working fine, but at the end of the call the page isn't updated.
I tried to remove all the old jquery code to avoid problems.
batarang and java console reports no errors.
the final ajax call is done and the result shown in a debug.
All seems to work fine, but the page isn't updated.
How can I find the problem?
thanks
Without seeing any code, it's difficult to answer but if you bind an event to an element and want to update something in the callback, you will have to use $apply
scope.$apply(function () {
// your code
});
$apply will trigger a $digest cycle, and should be used when you want to update something while being outside angular's context.
Most likely you are not handling your asynchronous calls correctly. It's impossible to tell from your question but it is a very common mistake with symptoms as you describe.
Make sure you are updating your model within the .then() method of a promise returned from an $http request. For example
someFnDoingHttpRequest().then(function(data){
// updated the model with the data
})
Also (another common mistake) make sure someFnDoingHttpRequest() returns a promise.
If you want to "find the problem" then you can use the following option.
Go to Internet Explorer (10 or 11).
Select "Internet Options" from the settings menu.
Go to the "Advanced" tab (the last tab)
Settings are listed and select "Display a notification about every script error"
Deselect the "Disable Script debugging (Internet Explorer)" and "Disable script debugging (Other)"
Run the program again, you will get notification about the real issue that happens while displaying actual result.

Webshims - Show invalid form fields on initial load

(Follow on questions from Placeholder Hidden)
I'd like my form to validate existing data when it is loaded. I can't seem to get that to happen
I jQuery.each of my controls and call focus() and blur(), is there a better way than this? I tried to call ctrl.checkValidity(), but it wasn't always defined yet. When it was, it still didn't mark the controls.
I seem to have a timing issue too, while the focus and blur() fire, the UI does not update. It's as if the Webshims are not fully loaded yet, even though this fires in the $.webshims.ready event.
I also tried to call $('#form').submit(), but this doesn't fire the events as I expected. The only way I could make that happen was to include an input type='submit'. How can I pragmatically case a form validation like clicking a submit button would?
Here's a jsFiddle that demonstrates the problem. When the form loads, I want the invalid email to be marked as such. If you click the add button it will be marked then, but not when initially loaded. Why?
Focus and blur in the control will cause it to be marked.
BUT, clicking ADD will too (which runs the same method that ran when it was loaded). Why does it work the 2nd time, but not when initially loaded?
updateValidation : function () {
this.$el.find('[placeholder]').each(function (index, ctrl) {
var $ctrl = $(ctrl);
if( $ctrl.val() !== "" && (ctrl.checkValidity && !ctrl.checkValidity()) ) {
// alert('Do validity check!');
$ctrl.focus();
$ctrl.blur();
}
});
}
I see this in FF 17.0.5. The problem is worse in IE9, sometimes taking 2 or 3 clicks of ADD before the fields show in error. However, I get errors on some of the js files I've liked 'due to mime type mismatch'.
This has to do with the fact, that you are trying to reuse the .user-error class, which is a "shim" for the CSS4 :user-error and shouldn't be triggered from script. The user-error scripts are loaded after onload or as soon as a user seems to interact with an invalid from.
From my point of view, you shouldn't use user-error and instead create your own class. You can simply check for validity using the ':invalid' selector:
$(this)[ $(this).is(':invalid') ? 'addClass' : 'removeClass']('invalid-value');
Simply write a function with similar code and bind them to events like change, input and so on and call it on start.
In case you still want to use user-error, you could do the following, but I would not recommend:
$.webshims.polyfill('forms');
//force webshims to load form-validation module as soon as possible
$.webshims.loader.loadList(['form-validation']);
//wait until form-validation is loaded
$.webshims.ready('DOM form-validation', function(){
$('input:invalid')
.filter(function(){
return !!$(this).val();
})
.trigger('refreshvalidityui')
;
});

Display n time ago on various items using jquery, [issue with new elements generated after the loading the DOM]

I am using Jquery plugin http://timeago.yarp.com/ for showing time.
Issue is timeago will not take effect for dynamically generated items.
$(document).ready(function() {
$(".timeago").timeago(); // works perfectly fine for the items which are loaded on page load
//$(".timeago").live(timeago()); // gives me an error ie timeago is not defined
//$(".timeago").live($(".timeago").timeago()); // gives me an error too much recursion.
jQuery.timeago.settings.allowFuture = true;
});
From some google search I got to know something ie:
Using live is the same as using bind, except that it is limited only to the events click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, and mouseup.
Now how can do it cause I dont have any click event? How can I bind this?
.live() and .bind() assign callbacks to event. In your case, you don't have an event to assign the function to and so it fails.
You can, in theory, assign your callback to a custom event. You will however have to manually trigger the event (using .trigger()) whenever your item is generated. For example:
$("abbr.timeago").live("timeago", function() {
$(this).timeago();
});
// ... and in the bit that generates your item
$new_item.trigger("timeago")
Demo: http://jsfiddle.net/ZjuW4/9
Of course, using .live() in this situation is purely academic and does not really serve a good purpose.
If you do have access to the code that's generating the items, you can simply chain in the call to .timeago() as the items are generated, i.e. http://jsfiddle.net/ZjuW4/3/
take a look in this topic
here was discussed how to put timeago on dynamically loaded items
for example the results of an ajax request.
Activate timeago on newly added elements only
PS: allowFuture does not have anything to do with putting timeago on newly created items on your page. it just allows dates in the future (f.e. "in 3 days", "next week")

Resources