1

I set a data attribute for a user on a link like this

  <input type="button" class="btn" data-user={"user": "<%= @user.name %>"}  value="Start" id="game">

In the javascript function that listens for the click event, I did a console.log(e.target) and it printed the whole thing to the console.

<input type="button" class="btn" data-user={"user": "<%= @user.name %>"}  value="Start" id="game">

If I do console.log(e) i.e. with no e.target, it logs the jquery event, but the data attribute is undefined

data: undefined

I'm trying to pull the username from the data attribute but don't know how to get it from this

<input type="button" class="btn" data-user={"user": "<%= @user.name %>"}  value="Start" id="game">

and I don't know why data is undefined when I log just the event.

I'd be very grateful if you can assist me with this. Thanks in advance.

6
  • 1
    Please show us the actual generated markup, that the browser sees. If the "markup" above is what the browser sees, that's not valid markup. Commented Mar 13, 2013 at 21:59
  • 2
    I don't think any of that is valid markup. Commented Mar 13, 2013 at 21:59
  • The attribute value needs to be in quotes: data-user="{'user': '<%= @user.name %>'}" or data-user="<%= @user.name %>" Commented Mar 13, 2013 at 22:00
  • console.log($(this).attr("data-user")) Commented Mar 13, 2013 at 22:00
  • check this answer with explanation stackoverflow.com/questions/11052806/… Commented Mar 13, 2013 at 22:01

2 Answers 2

4

Your HTML is ... unique? Instead of this:

data-user={"user": "<%= @user.name %>"}

Try this:

data-user="<%= @user.name %>"

Then you can get the data with the standard jQuery .data() technique (since you mentioned jQuery):

var user = $('#game').data('user');
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I actually had the html correct, but then changed it once I did some google searching and found some bad advice on another blog. I didn't realize, though, that you turned the id (#game)into the jquery selector to access the data attribute. Thanks
0

You can access the data from the DOM object as follows:

var data = $(e.target).attr("data-user");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.