Pergunta

I have INPUT HTML tag with type as hidden in view.It looks as follows:

     <input type="hidden" data-abc-value1="value1" data-abc-value2="value2" data-abc-
         value3="value3"/>

I would like to get the values of data- attributes(data-abc-value1,data-abc-value2,data-abc-value3) without passing element id to it.

Can i somehow find matching data-abc(which is common) attributes for the element and get its values.So that i can avoid dependency on element id to get data -* value.

Foi útil?

Solução

Try this code, this may help you

HTML

<input type="hidden" data-abc-value1="value1" data-abc-value2="value2" data-abc-value3="value3" />

Script

$('input[type="hidden"]').each(function(i, e){
    $.each(e.attributes, function(j,v){
        if(/^data-abc/.test(v.nodeName)) {
            console.log(v.nodeName, v.nodeValue);
        }
    });
});

Demo JS http://jsfiddle.net/UYNsw/

Outras dicas

jQuery doesn't provide a way to query by partial attribute names, so you're going to have to get all hidden inputs and then filter the results by attribute using a regular expression:

$(function() {
    var inputs = $('input[type="hidden"]').filter(function() {
        var attrs = this.attributes; //get attribute collection for this element
        for(var i=0; i<attrs.length; i++) {
            if(/data-abc-*/.test(attrs[i].name)) {
                return true; //adds this element to the jquery collection
            }
        }
        return false;
    });

    //do something with inputs

});

http://jsfiddle.net/UPH6R/1/

When jQuery is available use the .attr() function to get w3c invalid attributes. Also use .eq(0) to make sure you select the first and only 1 hidden input field. In case of more hidden input fields there's no guarantee this is gonna work.

var inp1 = $("input[type=hidden]").eq(0),
    val1 = inp1.attr("data-abc-value1"),
    val2 = inp1.attr("data-abc-value2"),
    val3 = inp1.attr("data-abc-value3");

Check out sample at jsFiddle http://jsfiddle.net/vijaypatel/xk42F/

$.fn.filterData = function (set) {
    var elems = $([]);
    this.each(function (i, e) {
        $.each($(e).data(), function (j, f) {
            if (j.substring(0, set.length) == set) {
                elems = elems.add($(e));
            }
        });
    });
    return elems;
}

$.each($('input').filterData('abc'), function (index, value) {
            alert($(this).attr('data-abc-value1'));
        });

you can get them by

$("input[type='hidden']").attr('data-abc-value1')
//or 
$('input[data-abc-value1]').attr('data-abc-value1')
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top