is not added to the input element
Correct, that's not how .data()
works. When use .data()
to add data, it's stored internally within jquery, so you read it again via jquery, not by looking at the html or using vanilla javascript to read it.
The initial value will be read from any matching data-
attributes, but after that it uses the internal value.
Example:
$(".add-new-item").click(function() {
var catid = $(this).data("catid");
$(".search-input").data("catid", catid);
});
$(".readdata").click(function() {
console.log($(".search-input").data())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type='button' class="readdata">Read Data</button>
<button type='button' class="add-new-item" data-catid="1">Add Data</button>
<input class="search-input" type="text" name="search" placeholder="Start typing to search">
<button type='button' class="readdata">Read Data</button>
There's also a difference in that .data()
will attempt to infer the data type for you (so you could get a number out) while .attr()
will always be a string.