Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript : how to distinguish between selected element list and form

Tags:

javascript

Here is the scripts: http://jsbin.com/itusut/6/edit

Hi, i have function:

function on(t, e, f) {
    if ( e.length ) {
        var l = e.length,
        n = 0;

        for ( ; n < l; n++ ) {
            e[n].addEventListener(t, f, false)
        }
    } else {
        e.addEventListener(t, f, false);
    }
}

if we do var handle = document.getElementsByClassName('some-class'); then handle is a node list.

if we do var handle = document.getElementById('an-id'); then handle is a single node.

The problem is, when i choose <form id="login-form"> it returns array not single element.

So, my on function is fail. The function use elm.length filter. Everything is ok, except for <form> . How to fix this? i know elm.length not work properly on single node <form> element.

Would you help? Thank you very much

like image 829
Slamet Bedjo Avatar asked Aug 15 '13 00:08

Slamet Bedjo


1 Answers

Form elements have a length property (to tell the number of fields in the form). The code you're using doesn't accurately detect whether the element is a DOM node, so it assumes that the form is a collection of DOM nodes.

If you need to bind elements, you're probably better off always passing in an array or array-like object, so that the function always iterates over the collection.

This could be as simple as wrapping the parameter in an array:

on('click', [formElement], callback);

Updated version of on where only lists are supported:
function on(type, elements, callback) {
    var length,
        i;
    length = 0;
    if (elements && elements.length) {
        length = elements.length;
    }
    for (i = 0; i < length; i += 1) {
        elements[i].addEventListener(type, callback, false);
    }
}
like image 92
zzzzBov Avatar answered Oct 28 '22 20:10

zzzzBov