Set generic "date - * " attributes with javascript;

Asked

Viewed 3,411 times

3

I need to retrieve all my date attributes, and set the information in 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?

I’m sorry but it’s really hard to find any reference;

  • Where do you want to put what? You can give an example of which data- should go where? want to put another HTML or a variable?

  • maybe this will help, http://stackoverflow.com/questions/12862423/regular-expression-in-data-attribute-jquery

4 answers

2

The function jquery.data don’t arrow the attribute data- it just writes to "memory".

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

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 attributes data-, in accordance with this answer.

Alternative

If you just need to write the data into the element and recover it only, you can use the jquery.data, no need for attributes.

Example of use:

$(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 must be something like:

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

For testing:

 $( 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
 });
  • I could never change the value of one data-attribute using .data(), always had to use .attr().

  • @Kaduamaral and it’s not that you’re right, at least in Sopt’s jquery it didn’t work (I tested it on the console) - jquery 1.7.1 -- apparently has nothing to do directly with the attribute data-

  • @Kaduamaral O data jQuery does not manipulate attributes, but properties of an (internal) object. See http://answall.com/a/50042

  • 1

    In fact, I explained it right here: http://answall.com/a/50355

2

There are two problems with your code.

One is the question you have about using jQuery to pick up/write on data-. The other problem is maybe why you didn’t get the results when you tested with data-.

Your HTML is

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

and added an event receiver to the li:

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

And inside the event receiver you’re using the $(this).prev(). One of the problems is right here. The prev() selects siblings, DOM elements that are on the same level and not ancestors. In the case of your input you really need to match the .closest() and the .find()

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

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

then you can set the data- or the value. I’m still not sure what you want to do but if you want to set or read the 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/input value:

.val('valor a setar'); // escrever no value do elemento
.val(); // só para ler

0

In jQuery to manipulate the attribute data-* use like this:

To catch: $('#campo').data('valor');
Setar: $('#campo').data('valor', 8);

0

I’ve developed an extension for 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.