I need to use jQuery to set the focus to the element with the minimum value of a specified attribute. For example, in this markup:
<input type='text' data-myAttr='5' />
<input type='text' data-myAttr='3' />
I want to set focus to the second input. It could be expressed in C# on an IEnumerable<T>
of elements on the page like this:
List<DomElement> elements; //Assume this is fu开发者_开发技巧ll of page elements
DomElement minElement = elements.OrderBy(e => e.attr("data-myAttr")).First();
minElement.Focus();
The context is that I have a web app (ASP.NET) involving several different jQueryUI modal dialogs used to edit different types of records. Each of them has a defined tab order. Depending on edit permissions, some fields on some modals are replaced with text (Labels instead of DropDownLists or TextBoxes). jQueryUI's normal behavior of defaulting to focusing the first focusable element in the dialog doesn't always work for me, so I need to set focus to the element in the modal with the minimum tab index.
Iterate over the collection, find the lowest value and set focus to it like this:
function setDialogFocus() {
var minValue;
var minItem;
$("input[type='text']").each(function() {
var val = parseInt($(this).attr("data-myAttr"), 10);
if (val && (!minItem || val < minValue)) {
minItem = this;
minValue = val;
}
});
if (minItem) {
$(minItem).focus();
}
}
This could also be done with .map()
like this:
function setDialogFocus() {
// get an array of all data attributes and their corresponding objects
var map = $("input[type='text']").map(function() {
var val = parseInt($(this).attr("data-myAttr"), 10);
if (val) {
return ({obj: this, value: val});
}
}).get();
// sort by value to find the lowest value
map.sort(function(a, b) {return a.value - b.value;});
if (map.length > 0) {
$(map[0].obj).focus();
}
}
An alternate approach would be to clone & sort. Easier (as in shorter), but potentially more overhead, especially if there are many fields.
var firstField = $('input[data-myAttr]').clone().sort(function(a, b) {
return parseInt($(a).attr('data-myAttr')) - parseInt($(b).attr('data-myAttr'));
}).first();
精彩评论