2

How can I check if a browser supports the formtarget or the form attribute?

Modernizr is no help here and I couldn't even find something on the web on the current state of form support in browsers. Although a quick test revealed all current browsers except IE 9 do support them.

So how can I check if a browser handles the form* attributes?

Daniel Rikowski
  • 71,375
  • 57
  • 251
  • 329

4 Answers4

2

Here you go:

if("formtarget" in document.createElement("input")){
    //good job, browser
}else{
    //nope
}
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • -1 According to this, `formtarget` is not supported on browsers that do support it. – user247702 Aug 28 '13 at 13:14
  • http://jsfiddle.net/ZXccw/ Outputs 'false' on Firefox 23, while it has been supported since Firefox 4. [Bugzilla ticket](https://bugzilla.mozilla.org/show_bug.cgi?id=566064) *2010-08-19 22:20:37 PDT This is now in the tree.* – user247702 Aug 28 '13 at 20:35
2

The form attribute on input is a special case. It was used before the HTML5 feature, to reference the parent form, but now it's used as an attribute as well, so you will have false positives on IE.

There is a checking function but it involves interaction with DOM which will probably affect performance, but here you go anyway. Hope it helps.

function testInputFormSupport() {
    var input = document.createElement('input'),
         form = document.createElement('form'),
         formId = 'test-input-form-reference-support';
    // Id of the remote form
    form.id = formId;
    // Add form and input to DOM
    document.body.appendChild(form);
    document.body.appendChild(input);
    // Add reference of form to input
    input.setAttribute('form', formId);
    // Check if reference exists
    var res = !(input.form == null);
    // Remove elements
    document.body.removeChild(form);
    document.body.removeChild(input);
    return res;
}
Sev
  • 1,982
  • 1
  • 16
  • 27
1

Have a look at this site. It covers all the new form features and gives a handy little function to test the support of an attribute

// Function to test for attribute support
function elSupportsAttr(el, attr) {
  return attr in document.createElement(el);
}
Andreas
  • 21,535
  • 7
  • 47
  • 56
  • Wufoo does not cover *all* new form features, at least `form` is not mentioned. But the test function works. – Daniel Rikowski Jun 24 '12 at 15:15
  • 1
    -1 this won't work. `"form" in document.createElement("input")` returns `true` on IE8 (see @Sev's answer for the reason). `"formaction" in document.createElement("input")` and others return `false` on any browser that should support it. – user247702 Aug 28 '13 at 12:57
0

Try

if ("attribute" in document.createElement("tag"))

from How can I tell of a HTML attribute exists or not, using Javascript

Community
  • 1
  • 1
Niall
  • 425
  • 6
  • 14