views:

422

answers:

2

I need a function to select all elements with a custom attribute, and take its name and value. for example:

<input type="text" my:name="koni" my:age="20" my:city="New York" />

Note that my is always the same, but that behind not. in my function i then want to say:

var attr = //here should be the attribute (attr, or attr2)

and

var value = //here should be the value (test, or hello)

how can i make that?

Edit: sorry, forgot to paste the html.

i want to loop throu each input that has such custom my attributes, and get the value and the key in an array. for this example, i should have:

key = name, value = koni

and

key = age, value = 20

...

A: 

You should be able to select

<div cheese="brie">foobar</div>

using

var items = $("div[cheese]");
Emyr
this will not work, since the element should be generic as well as the attribute. the attribute starts with "my:", but the end is generic
k0ni
+1  A: 

Hello,

I don't think there is an easy way to do this in one easy swoop using a jquery selector, since you don't know the exact name of the attribute you're looking for. (You only know its prefix.) So, perhaps you could just loop through all inputs, and walk through the attributes checking for any desired matches?

$('input').each(function() {
    var result = {};                                // to hold any results we might find
    var attrs = this.attributes;                    // this array is provided by the DOM
    for (var idx in attrs) {
        var attrName = attrs[idx].name;
        if (/^my:/.test(attrName)) {                 // must start with this hardcoded pattern
            var key = attrName.substring(3);        // skip first 3 chars
            var value = $(this).attr(attrName);
            result[key] = value;
        }
    }
    // do something with your result obj here...
    if (result['name']) {
        alert('found input with my:name of ' + result['name']);
    }
});

I'm putting the results in an object instead of an array (which seems to make more sense) but this should give you the general idea should you care to refine this at all.

Best of luck!

Funka
thank you, i think i can build on that!
k0ni