Reputation: 2901
I have some input tags like this:
<input data-role="none" id="TaskActionList.SpaceId" type="hidden" value="@Model.CombinedAvailableSpaces.Single().SpaceId" name="" data-inputname="TaskActionList" data-propertyname="SpaceId" data-singlespace="true"/>
(I have about 3 of the exact same input tag on my page)
I want to get the last attribute value: 'true' from the very last attribute on my input tag. I've tried this jquery but I keep getting a value of undefined:
$('input').attr('data-singlespace')
I should get back the word 'true' but instead I get undefined. Why could this be?
Upvotes: 1
Views: 52
Reputation: 150070
The .attr()
method returns the specified attribute from the first element in the jQuery object. In your case the jQuery object $('input')
selects every input element on the page, so you're trying to get that attribute from the first input where (presumably) the attribute isn't defined.
Change your selector to be sure to get the correct element.
Upvotes: 1
Reputation: 5443
you could also try this:
$('input[data-singlespace]').data('singlespace');
Upvotes: 1
Reputation: 55750
It is a better idea to use .data()
method to access custom attributes
$('input').data('singlespace')
The problem might also be because of multiple inputs.
Put the code inside $.each
$('input').each(function() {
console.log($(this).data('singlespace'));
});
Or use eq
to target a specific input based on the index as the selector is too specific.
$('input').eq(1).data('singlespace') ;
// Gets the 2nd input
Upvotes: 2