Set generic "data - *" attributes with javascript;

3

I need to retrieve all my data attributes, and set the information to a specific date attribute.

Example:

<div class="box_campo">
    <input type="text" data-valor="0">
    <ul>
        <li>apenas exemplo</li>
    </ul>
</div>

<div class="box_campo">
    <input type="text" data-campo="0">
    <ul>
        <li>apenas exemplo</li>
    </ul>
</div>

<script >
 $( document ).on( "click", ".box_campo ul li", function() {

    $(this).prev('input').attr('data-AQUI ESTA A DUVIDA', valor);

 });
</script>


how can I write the function so that it can change both the date-field and the date-value?

Sorry, but it's really hard to find some reference;

    
asked by anonymous 13.07.2015 / 21:59

4 answers

2

There are two problems in your code.

One of them is the question you have about using jQuery to get / write to data- . The other problem is maybe why you did not get the result when you tested with data- .

Your HTML is

<div class="box_campo">
    <input type="text" data-campo="0">
    <ul>
        <li>apenas exemplo</li>

and put an event dropper for li :

$(document).on("click", ".box_campo ul li", function() {

And within the event observer you are using $(this).prev() . One of the problems is exactly here. prev() selects siblings, DOM elements that are at the same level as non-ancestors. In the case of your input you have to match .closest() and .find()

To "find" this input from $(this) accurate:

$(this).closest('.box_campo').find('input')

Then you can set data- or value . Still not sure what you want to do but if you want to set or read data- you can use

.data('nomedocampo', 'valor a atribuir'); // escrever no elemento
.data('nomedocampo'); // só para ler

If you want to set or read the value / value of the input:

.val('valor a setar'); // escrever no value do elemento
.val(); // só para ler
    
13.07.2015 / 22:47
2

The function jquery.data does not pass the data- attribute it just does the recording in the "memory".

In case you can create a function using jQuery.fn.extend , like this:

jQuery.fn.extend({
  "dataAttr": function(name, value) {
    if (typeof value === "undefined") {
        return $(this).attr("data-" + name);
    }

    return this.each(function() {
        $(this).attr("data-" + name, value);
    });
});

 $( document ).on( "click", ".box_campo ul li", function() {

    $(this).prev('input').dataAttr('ATRIBUTO', valor);

 });
  

Note: jquery.data works with the data- attributes, as this answer .

Alternative

If you only need to write the data to the elements and retrieve them only, you can use jquery.data , without need attributes.

Example usage:

$(this).prev('input').data( "foo", 52 );
$(this).prev('input').data( "bar", { myType: "test", count: 40 });
$(this).prev('input').data( { baz: [ 1, 2, 3 ] });
$(this).prev('input').data( "foo" ); // 52

Your code should be something like:

 $( document ).on( "click", ".box_campo ul li", function() {
    $(this).prev('input').data('Sua chave', valor);
 });

To test:

 $( document ).on( "click", ".box_campo ul li", function() {
    alert( $(this).prev('input').data('teste') );//Retorna undefined

    $(this).prev('input').data('teste', 'valor');

    alert( $(this).prev('input').data('teste') );//Retorna valor

    alert( $(this).prev('input').attr('data-teste') );//Provavelmente retorna undefined
 });
    
13.07.2015 / 22:12
0

In jQuery to manipulate the data-* attribute use:

To fetch: $('#campo').data('valor');
To set: $('#campo').data('valor', 8);

    
13.07.2015 / 22:12
0

I've developed an extension to jQuery that might help.

(function(jQuery) {
    jQuery.fn.attrData = function(k, v){

        var attrs = jQuery(this[0].attributes);
        var attrsData = attrs.filter(function(index){
            return this.name.match(/^data/);
        });

        var len = attrsData.length;

        if(len > 0) {
            for(var i = 0; i < len; i++){
                if(attrsData[i].name == 'data-'+k){
                    if(v == undefined){
                        return attrsData[i].value;
                    }else{
                        var data = attrsData[i].name; 
                        jQuery(this).attr(data, v);
                        return v;
                    }
                }
            }
        }else{
            null;
        }
    };
})(jQuery);

jQuery(input).attrData('valor'); // 0
jQuery(input).attrData('valor', 1); // 1
    
13.07.2015 / 23:18