cebo
cebo

Reputation: 818

jquery .attr() returning undefined

I have a form element:

<form name="editTourneyForm" data-tourney-id="28">

and a jquery selector:

$('#editTourneyForm').attr('data-tourney-id')

When I try to access either attribute (data or name) via .attr() it returns undefined. When I inspect the jQuery object I can't find either attribute anywhere (granted I am not farmiliar with the jQuery object structure) although both the attr and data properties have length=2. I have no idea what might be going wrong. The form is not generated at runtime so it shouldn't be an issue of dynamic content not being selected.

I had already had it working before and I made some changes to other parts of my project and now this is broken somehow, any ideas?

Upvotes: 0

Views: 350

Answers (2)

Pranav Rustagi
Pranav Rustagi

Reputation: 2731

Notice that you don't have any id for the element. It just has the name attribute on the basis of which you are trying to select.

Use the below selector to do so :

$('form[name=editTourneyForm]')

Besides that, although the attribute you are trying to access can be accessed using .attr(), but data-attributes are recommended to be accessed using .data(). Do that like this :

$('form[name=editTourneyForm]').data('tourney-id');

Upvotes: 1

polyglot
polyglot

Reputation: 862

It's a JQuery data() method. Use $('form[name="editTourneyForm"]').data('tourney-id') instead. Please check their doc.

Make sure to use correct selector.

Upvotes: 0

Related Questions