将重点放在IE中的输入框上

时间:2013-10-03 19:27:52

标签: javascript forms internet-explorer

我正在处理的Web应用程序中存在以下情况:

我有一个带有一组索引字段值的表单,用户将信息输入到该表单中,然后将表单提交给服务器。字段验证在服务器上进行。如果发现任何字段无效,则重新显示表单,并且我希望输入焦点自动转到第一个无效字段。我有代码来实现它,但问题是焦点不是放在IE 10中的字段上(但它被放置在Firefox中)。

  placefocusonfirstinvalidindexfield();

  // After an attempt to upload has failed due to one or more invalid fields, then place the input focus automatically on the first
  // invalid field:
  function placefocusonfirstinvalidindexfield() {
    var hasattemptedupload = '@Model.HasAttemptedUpLoadNumeric';
    if (hasattemptedupload == 1) {
      var indexfirstinvalidfield = '@Model.GetIndexOfFirstInvalidField()';
      // focusIndexField(indexfirstinvalidfield);
      setTimeout(focusIndexField(indexfirstinvalidfield), 100);
    }
  }

  function focusIndexField(fieldindex) {
    var control = document.getElementById("field" + fieldindex);
    control.focus();
  }

在上面的代码中,我已确认正在引用正确的字段。一切似乎都应该如此,除了在过程结束时,IE10不会将焦点放在引用的字段上。为什么不呢?我需要做些什么才能实现这一目标?

2 个答案:

答案 0 :(得分:1)

在控制台中尝试使用IE进行测试。当测试焦点在此页面上的“发布您的答案”文本区域时,以下代码工作正常。

setTimeout(function() { document.getElementById("wmd-input").focus() }, 5000);

也许你的代码中有其他东西干扰焦点?您是否尝试过延长超时值以查看它是否与此有关?

答案 1 :(得分:0)

你正试图围绕DOM加载这个行吗?

setTimeout(focusIndexField(indexfirstinvalidfield), 100);

该行无法正常工作。 focusIndexField立即执行,并且setTimeout函数将函数的响应延迟100 ms。

这可以按预期工作:

setTimeout(function() {focusIndexField(indexfirstinvalidfield)}, 100);

但是,这不是一个好的解决方案。代码应该在文档准备就绪时执行。

相关问题