Really yes you can , from HTML 5 it is possible to use the property data-*
which:
Provides read / write access to all attributes of
custom data ( data-*
) set in the element. East
Access is available in both HTML and within the DOM. It's a map
of DOMString, an entry for each custom data attribute.
Note that the property of the data set can be read,
but do not write directly. Instead, all scriptures should
be for the individual properties within the data set,
which in turn represent the data attributes. Keep in mind
also that an HTML data attribute and its DOM dataset.property
corresponding do not share the same name, but they are always
similar.
See the following input
:
<input id="ibxPersona"
data-dni="X123456"
data-ciudad="New York"
data-profesion="Informático"
value="John Doe" />
Apart from the traditional value
, from HTML 5 you can add additional information in the form: data-identificador
, which can be recovered as follows: elemento.dataset.identificador
.
But the data-*
property is much more powerful. We can modify it at runtime, deleting / modifying / adding information.
Let's see in example:
/*Referencia al input*/
const ibxPersona = document.querySelector('#ibxPersona');
/*Referencia a todo el dataset por simplicidad*/
const dataPersona = ibxPersona.dataset;
/*Valores que ya existen*/
var personaDNI = dataPersona.dni;
var personaCiudad = dataPersona.ciudad;
var personaProfesion = dataPersona.profesion;
console.log("DNI:\t" + personaDNI);
console.log("Ciudad:\t" + personaCiudad);
console.log("Prof:\t" + personaProfesion);
/*Se le puede agregar información de forma dinámica*/
dataPersona.java = true;
console.log("Ahora " + ibxPersona.value + " aprendió Java: " + dataPersona.java);
/*Se le puede quitar información*/
delete dataPersona.profesion;
/*Se puede modificar información*/
dataPersona.profesion=personaProfesion+", Escritor";
/*Cómo se muestra el data set*/
console.log(dataPersona);
<input id="ibxPersona" data-dni="X123456" data-ciudad="New York" data-profesion="Informático" value="John Doe" />
It must be said that before data*
one could resort to certain tricks to pass several elements, which was very useful in some cases. But this new functionality makes that history.
In prehistory one could do things like this:
<select name="selTest">
<option value="3|5|8">Opc 1</option>
<option value="2|4|6">Opc 2</option>
</select>
Here the value
was serving me to pass three values in one .