Jessie boely
Jessie boely

Reputation: 13

Get Data Value from Parent or Closest Div

I have this function that I am trying to get the data value of the outside div but I can't seem to get it to work, here is my code:

I want the variable test to have the value of 1000. But I get undefined.

function View() {
  var test = $(this).Parent().val;
}

function Hide() {
  var test = $(this).Parent().val;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-value="1000">
  <a onclick="View();">View</a>
  <a onclick="Hide();">Hide</a>
</div>

Upvotes: 0

Views: 59

Answers (2)

Sanjit Bhardwaj
Sanjit Bhardwaj

Reputation: 893

Here is a JQuery solution for the problem.

$('#hide').click(function() {
  alert($(this).parent().data('value'));
})

$('#view').click(function() {
  alert($(this).parent().data('value'));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-value="1000">
  <a id="view">View</a>
  <a id="hide">Hide</a>
</div>

Upvotes: 0

jcal
jcal

Reputation: 875

function View(anchor) {
 var test = $(anchor).parent().data('value');
 console.log(test);
}

function Hide(anchor) {
 var test = $(anchor).parent().data('value');
  console.log(test);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-value="1000">
<a onclick="View(this);">view</a>
<a onclick="Hide(this);">hide</a>
</div>

Upvotes: 3

Related Questions