Reputation: 70
I am trying to set the focus on the first control in a form when I first enter the page. This sometimes works, and sometimes doesn't - the cursor is not set in the field but the address in the address bar has the focus. The example below doesn't work.
$(document).ready(function () {
$(".focus").first().focus();
var pickerOpts1 = {
defaultDate: "+0", //Used to move the current date cursor by n-days
dateFormat: "mm/dd/yy",
showOtherMonths: true,
changeMonth: true,
changeYear: true,
yearRange: '1970:2020'
};
$("#Sin").mask("999-999-999");
$("#successorHolderSin").mask("999-999-999");
$(".sinNumber").mask("999-999-9999");
$(".datepicker").mask("99/99/9999");
$(".datepicker").datepicker(pickerOpts1);
var dateFormat = "dd/mm/yy"; // en-gb date format
jQuery.validator.addMethod('date', function (value, element, params) {
if (this.optional(element)) {
return true;
};
var result = false;
try {
$.datepicker.parseDate(dateFormat, value);
result = true;
}
catch (err) {
result = false;
}
return result;
}, '');
});
<%:Html.DropDownListFor(r => Model.LegislationId, legislationTypeItems, new { @class = "focus" })%>
However, when I go to look at the source code after I've run the page or use the Developer Tools to look for it the class shows up in the tag:
<select class="focus" data-val="true" data-val-number="The field LegislationId must be a number." id="LegislationId" name="LegislationId">
Can you tell me what I might be missing? The jQuery files I'm using are:
<script src="../../Scripts/jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.maskedinput-1.3.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-datepicker.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.js" type = "text/javascript"></script>
Upvotes: 0
Views: 252
Reputation: 628
$(".focus")
returns an array of elements even if only one element is matched to the selector.
So try this:
$(".focus").first().focus();
Edit: To make it run on page load you need to wrap it like this:
$(function() {
$(".focus").first().focus();
});
Upvotes: 1