简体   繁体   English

用于按钮元素的HTML5表单属性的Internet Explorer问题

[英]Internet Explorer issue with HTML5 form attribute for button element

in HTML5, there is the form attribute. 在HTML5中,有form属性。 Basically 基本上

<form id="myform" method="get" action="something.jsp">
    <input type="text" name="name" />
</form>
<input type="submit" form="myform" />

the above code is not working in IE. 上面的代码在IE中不起作用。 Can any one help me how to solve this requirement. 任何人都可以帮我解决这个问题。

I've used the following javascript and jQuery to submit the form, but I facing the Ajax issue. 我使用了以下javascript和jQuery来提交表单,但我遇到了Ajax问题。 where my page is reloading. 我的页面正在重新加载。

document.getElementById("myForm").submit();

$("#myForm").submit();

How can I submit my form where my page should not load. 如何在我的页面不应加载的地方提交表单。 I am using Anguler JS Ajax. 我正在使用Anguler JS Ajax。

IE does not support HTML5 form attribute for <input> or <button> element yet. IE尚不支持<input><button>元素的HTML5 form属性。

If you want to associate an outer input element with the form, you can duplicate a "shadow" as an invisible input field inside your form, and attach an event handler to the form's onsubmit event. 如果要将外部输入元素与表单相关联,可以将“阴影”复制为表单内的不可见输入字段,并将事件处理程序附加到表单的onsubmit事件。 When user submits the form, update the value inside. 当用户提交表单时,更新其中的值。

The following polyfill (requires jQuery) emulates the feature. 以下polyfill(需要jQuery)模拟该功能。 It makes the input elements with form attribute act like they are inside the form: 它使具有form属性的输入元素form得像它们在表单中:

(function($) {
  /**
   * polyfill for html5 form attr
   */

  // detect if browser supports this
  var sampleElement = $('[form]').get(0);
  var isIE11 = !(window.ActiveXObject) && "ActiveXObject" in window;
  if (sampleElement && window.HTMLFormElement && sampleElement.form instanceof HTMLFormElement && !isIE11) {
    // browser supports it, no need to fix
    return;
  }

  /**
   * Append a field to a form
   *
   */
  $.fn.appendField = function(data) {
    // for form only
    if (!this.is('form')) return;

    // wrap data
    if (!$.isArray(data) && data.name && data.value) {
      data = [data];
    }

    var $form = this;

    // attach new params
    $.each(data, function(i, item) {
      $('<input/>')
        .attr('type', 'hidden')
        .attr('name', item.name)
        .val(item.value).appendTo($form);
    });

    return $form;
  };

  /**
   * Find all input fields with form attribute point to jQuery object
   * 
   */
  $('form[id]').submit(function(e) {
    var $form = $(this);
    // serialize data
    var data = $('[form='+ $form.attr('id') + ']').serializeArray();
    // append data to form
    $form.appendField(data);
  }).each(function() {
    var form = this,
      $form = $(form),
      $fields = $('[form=' + $form.attr('id') + ']');

    $fields.filter('button, input').filter('[type=reset],[type=submit]').click(function() {
      var type = this.type.toLowerCase();
      if (type === 'reset') {
        // reset form
        form.reset();
        // for elements outside form
        $fields.each(function() {
          this.value = this.defaultValue;
          this.checked = this.defaultChecked;
        }).filter('select').each(function() {
          $(this).find('option').each(function() {
            this.selected = this.defaultSelected;
          });
        });
      } else if (type.match(/^submit|image$/i)) {
        $(form).appendField({name: this.name, value: this.value}).submit();
      }
    });
  });


})(jQuery);

Live version: http://jsfiddle.net/hbxk4e61/ 实时版: http//jsfiddle.net/hbxk4e61/

By the way, you can check this page to test how many HTML5 features your browser currently supports. 顺便说一句,您可以查看此页面以测试您的浏览器当前支持的HTML5功能的数量。 For example, I'm using Chrome 31 and it does support this attribute. 例如,我使用的是Chrome 31,它确实支持此属性。

Chrome目前支持该功能

Well, IE basically does not support form attribute in input, but you could use javascript to submit your form: 好吧,IE基本上不支持输入中的表单属性,但您可以使用javascript来提交表单:

document.getElementById("myForm").submit();

or jQuery 或jQuery

$("#myForm").submit();

As far as I can tell, Internet Explorer does not (up to IE10, at least) support the form attribute. 据我所知,Internet Explorer不支持(至少IE10)支持form属性。

You can either polyfill this in javascript, or move the input to sit inside the relevant form. 您可以在javascript中对此进行填充,也可以将input移动到相关表单中。 This has already been answered elsewhere though: https://stackoverflow.com/a/16694990/13019 这已经在其他地方得到了回答: https//stackoverflow.com/a/16694990/13019

<form id="form-any-name">
   <input type="button" value="Submit" class="myButton" />
</form>
<button type="submit">Submit</button>

<script type="text/javascript">
    $(document).ready(function() {
        $('button[type=\'submit\']').on('click', function() {
            $("form[id*='form-']").submit();
        });
    });
</script>

Since all projects has included jquery 100% :) you can define in external or any included js file the on document ready function to catch the submit button clicked outsiie form by catching all forms id starting with form- so it catch forms on different page with different names so you do not have to repeat the very same jquery code snipet 由于所有项目都包含了jquery 100%:)你可以在外部或任何包含的js文件中定义文档就绪函数来捕获提交按钮点击外包形式通过捕获所有表单id从表单开始 - 所以它捕获不同页面上的表单不同的名称,所以你不必重复相同的jquery代码snipet

From @Voldemaras Birškys' answer, I've improved his script to work as a polyfill so you can still have the form attribute no your button and it will work as if EDGE/IE would respect the form attribute. 从@VoldemarasBirškys的回答中,我已经改进了他的脚本作为polyfill工作,所以你仍然可以使用form属性而不是你的按钮,它就像EDGE / IE会尊重form属性一样。

<form id="form-any-name">
   <input type="button" value="Submit" class="myButton" />
</form>
<button type="submit" form="form-any-name">Submit</button>

<script type="text/javascript">
$(document).ready(function() {
    $('button[type=\'submit\']').click(function (e) {
        var formId = $(e.target).attr("form");
        $("form[id*="+formId+"]").submit();
    });
});
</script>

The main difference is that now we include form on the external submit button. 主要区别在于现在我们在外部submit按钮上包含form Also, inside the click handler I just use the event to get the target element and from id discover the id of the target form. 此外,在click处理程序中,我只使用事件来获取target元素,并从id中发现目标表单的id

:) :)

If you send form via ajax and use vanilla js, you can add inputs with "form" attribute like below: 如果您通过ajax发送表单并使用vanilla js,则可以添加带有“form”属性的输入,如下所示:

function sendViaAjax(event, callback) {
    event.preventDefault();
    var form = event.target;
    var formId = form.id;
    var url = form.getAttribute('action');
    var method = form.getAttribute('method');
    var data = new FormData(form);
    if(isInternetExplorer() && formId) {
        var formInputs = document.querySelectorAll('input[form="'+formId+'"], textarea[form="'+formId+'"], select[form="'+formId+'"]');
        [].forEach.call(formInputs, function (el) {
            var inputName = el.getAttribute('name');
            data.append(inputName, el.value);
        });
    }
    var xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.onload = function () {
        // something
    };
    xhr.onerror = function () {
       // something
    };
    xhr.send(data);
}

function isInternetExplorer() {
    return (navigator.appName == 'Microsoft Internet Explorer' ||
        !!(navigator.userAgent.match(/Trident/) ||
            navigator.userAgent.match(/rv:11/)) ||
        (typeof $.browser !== "undefined" && $.browser.msie == 1));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM