Please take note that jQuery .data()
is not updated when you change html5 data-
attributes with javascript.
If you use jQuery .data()
to set data-
attributes in HTML elements you better use jQuery .data()
to read them. Otherwise there can be inconsistencies if you update the attributes dynamically. For example, see setAttribute()
, dataset()
, attr()
below. Change the value, push the button several times and see the console.
$("#button").on("click", function() {_x000D_
var field = document.querySelector("#textfield")_x000D_
_x000D_
switch ($("#method").val()) {_x000D_
case "setAttribute":_x000D_
field.setAttribute("data-customval", field.value)_x000D_
break;_x000D_
case "dataset":_x000D_
field.dataset.customval = field.value_x000D_
break;_x000D_
case "jQuerydata":_x000D_
$(field).data("customval", field.value)_x000D_
break;_x000D_
case "jQueryattr":_x000D_
$(field).attr("data-customval", field.value)_x000D_
break;_x000D_
}_x000D_
_x000D_
objValues = {}_x000D_
objValues['$(field).data("customval")'] = $(field).data("customval")_x000D_
objValues['$(field).attr("data-customval")'] = $(field).attr("data-customval")_x000D_
objValues['field.getAttribute("data-customval")'] = field.getAttribute("data-customval")_x000D_
objValues['field.dataset.customval'] = field.dataset.customval_x000D_
_x000D_
console.table([objValues])_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<h1>Example</h1>_x000D_
<form>_x000D_
<input id="textfield" type="text" data-customval="initial">_x000D_
<br/>_x000D_
<input type="button" value="Set and show in console.table (F12)" id="button">_x000D_
<br/>_x000D_
<select id="method">_x000D_
<option value="setAttribute">setAttribute</option>_x000D_
<option value="dataset">dataset</option>_x000D_
<option value="jQuerydata">jQuery data</option>_x000D_
<option value="jQueryattr">jQuery attr</option>_x000D_
</select>_x000D_
<div id="results"></div>_x000D_
</form>
_x000D_