How to change the value of a "date" attribute in Jquery?

Asked

Viewed 12,033 times

11

I have an attribute data-order on a button and I want it to be incremented as I go adding new ones days to my list by clicking the button, so will have:

day-1
day-2
day-3
day-4

... and so on. Does anyone know how I can increase this value in jQuery?

P.S.: The button has a unique ID. I just don’t know how to do the increment.

EDIT: The question is not about concatenation, but about changing the value of data-order. I only have one of those attributes and I want to change its value day-1 for day-2.

5 answers

11


  • Exactly what I was looking for man, vlw! o/

  • If possible, create an example using the tool trecho de código here on Sopt. So, if for some reason there is a problem with the code posted on Jsfiddle, the question will be useful.

6

Other answers are assuming that you intend to use exclusively the method .data jQuery, and they seem to be correct, but it’s good to make a distinction: the attributes data-* HTML5 are not the same thing that the data stored by jQuery through the method .data. jQuery stores this data internally, and this is not reflected in the original element. Example.

If for some reason you want to update the element itself, don’t assign using .data, but using .attr. The reading should also be done in the same way - because the .data just cache the first value found, then no longer query the element.

var valor = $(this).attr('data-order').split('-')[1];
valor++;
$(this).attr('data-order', 'day-' + valor);

Example in jsFiddle. If you inspect the button in the browser, you will see that it actually has the attribute data-order with an updated value.

5

I leave one more answer (for modern browsers) which is using the HTML5 API.

Actually it won’t take jQuery for this, you can use the dataset.

The API is simple:

Dataset element..name // to read
Dataset element..name = 'new value' // to assign

Example:

var el = document.querySelector('#user');
var resultados = document.querySelector('#resultados');

// visualizar os campos data- 
// repare que pode verificar a existência de campos como "dateOfBirth" que não existe ainda, vai dar false
resultados.innerHTML = [el.dataset.id, el.dataset.user, !!el.dataset.dateOfBirth].join(' - '); 

el.dataset.dateOfBirth = '1960-10-03'; // settar a data.
resultados.innerHTML += ' - ' + el.dataset.dateOfBirth;
<div id="user" data-id="1234567890" data-user="johndoe">John Doe</div>

<div id="resultados"></div>

To make with pure JS in older browsers that do not support HTML5 can use getAttribute/setAttribute.

Note: as the @mgibsonbr referred to the jQuery does not change the same property that pure Javascript changes!

$(el).data('foo', 'bar'); // seta o valor
$(el).data('foo'); // dá bar
el.dataset.foo;    // dá undefined

Ai, ai... -1 for the jQuery.

4

data-* are customizable attributes of HTML elements, it is stored as a string property in the element’s dataset object. If you’re saving a list of values in it, you’re actually concatenating string.

For example:

var num = 0; // a fins de exemplo
$('#meu_botao').data('order', $('#meu_botao').data('order') + ', day-' + num++);

This can be added to the click event that will result in adding values to the attribute data-order, but it’ll stay that way:

'day-1, day-2, day-3' // e por ai vai, conforme for sendo adicionado

You can break this string later in an Array to handle the values for example:

$('#meu_botao').data('order').split(', '); // ["day-1", "day-2", "day-3"]

EDIT (after better explanation of the question):

In case you want to increment the value of day-{n} contained in date, you can use the String.prototype.match to take the existing value.

var num = $('#meu_botao').data('order').match(/day-([0-9]*)/), num = num && + num[1] || 0;
$('#meu_botao').data('order', 'day-' + num++);

This way you will not need to cache the number in a variable and will always be able to use the value contained in data-*

  • That’s a good answer, but that’s not exactly what I was asking. I was asking about changing the value of data-order of day-1 for day-2.

  • for the date attribute use the function http://api.jquery.com/data instead of attr ... reason: http://stackoverflow.com/questions/72619/jquery-datavs-attr

  • 1

    @Dennisbraga ah, I didn’t quite understand, I thought you were looking for an orderly list, but then Daniel’s response satisfies. I will only correct the issue of attr to date, because it is ideal with jquery.

  • I liked Edit asked to the question. Very good! This of not needing to cache the result, is show! D

  • @Dennisbraga I’m happy to be able to help, I improved the syntax in case the value date('order') comes empty not give error in your code. Hug!

1

date attributes can be changed with the jQuery date method a point solution may be as follows:...

var order = $("#meu_elemento").data("order");
var indice = +(order.split("-")[1]);
indice++;
$("#meu_elemento").data("order", "day-" + order);

Browser other questions tagged

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