A. Hasemeyer
A. Hasemeyer

Reputation: 1734

JQuery onclick data attribute "undefined"

I am having an issue pulling the data attributes out of an input when using onclick="javascript()" syntax.

Here is a jsfiddle of what I am trying:

https://jsfiddle.net/123umaon/2/

<div>
  <input onclick="Test();" type="button" value="test" data-section="thisSection"/>
</div>

function Test(){
var test = $(this).data('section');
alert(test);
}

I want to be able to pull the value of 'data-section' with the onclick action. But in my example it always comes back undefined.

Upvotes: 0

Views: 850

Answers (4)

Jason Dimmick
Jason Dimmick

Reputation: 500

function Test(btn){
var test = $(btn).attr("data-section");
alert(test);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <input onclick="Test(this);" type="button" value="test" data-section="thisSection" />
</div>

The problem is with your selector. "$(this)" in your example returns a reference to the function Test. Instead pass in this to the function and select off of the passed value.
Also, I would use the jQuery attr() funtion to set and return values on a custom property.

Upvotes: 1

Alex Melluzzo
Alex Melluzzo

Reputation: 73

Your function passes in the "Window" object, you'd need to refine what you're passing through.

For getting the data-section attribute, you can use the .getAttribute() method on the element. It works similarly to .setAttribute().

https://www.w3schools.com/jsref/met_element_getattribute.asp

Upvotes: 0

Jorjon
Jorjon

Reputation: 5434

You need to reference the current event. In the Test() function context, this refers to the window, instead of the DOM element.

$('#testOut').val("TEST TEST");

function Test(){
var test = $(event.currentTarget).data('section');
alert(test);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <input onclick="Test();" type="button" value="test" data-section="thisSection"/>
</div>

Note: The window.event variable I'm using here is frowned upon on new code.

Upvotes: 3

Ankur Mishra
Ankur Mishra

Reputation: 1296

$('#testOut').val("TEST TEST");

function Test(selector){
	var test = selector.data('section');
  alert(test);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <input onclick="Test($(this));" type="button" value="test" data-section="thisSection"/>
</div>

Upvotes: 2

Related Questions