Liran H Liran H - 7 months ago 38
Javascript Question

jQuery .prop() returns undefined, while .attr() works as expected

I am simply trying to get a couple of properties from two elements. Getting the property "value" from the input element works as expected. The problem is with getting the property "data-detail" property from the button element. It returns undefined when using .prop(), but works as expected when using .attr().

Can anyone explain this odd behaviour I am witnessing?

HTML

<div class="formRow">
<label for="firstName">First name</label>
<div class="detailsControlBtns">
<button id="editFirstName" class="btn ctaBtn greenBtn editBtn">Edit</button>
<button class="btn ctaBtn greenBtn saveBtn" data-detail="firstName">Save</button>
<button id="closeFirstName" class="btn ctaBtn greyBtn closeBtn">Close</button>
</div>
<input type="text" id="firstName" name="firstName" value="[+firstName+]" readonly>
</div>


JS

$(".saveBtn").on("click", function() {
var saveBtn = $(this);
// The following statement yields undefined. When using .attr() it works as expected.
var detail = saveBtn.prop("data-detail");
var relevantInput = saveBtn.parent().next();
// The following statement works as expected.
var value = relevantInput.prop("value");
// ...
});

Answer

.data() is for user defined data and .prop() actually updates/adds a property on the DOM element.

You should also use .data() instead .attr() so it would be:

$(".saveBtn").on("click", function() {
    var saveBtn = $(this);
    var detail = saveBtn.data("detail");
    var relevantInput = saveBtn.parent().next();
    var value = relevantInput.prop("value");

});

So, if you set the .prop("data-detail","newValue"); you will be able to get it the same way : .prop("data-detail"); , but note that you won't be able to get that value with .data() nor the newValue would be accessible with .attr()