Reputation: 3
I'm pretty sure the solution is staring at me in the face, but I can't see it!
This is what I want to achieve:
When a div is clicked, find the clicked div's value (not text), and console log it out. But when I do that, it returns an empty value instead.
What am I doing wrong? Thanks in advance.
HTML
<div id="d4" class="dice" value="4">?</div>
<div id="d6" class="dice" value="6">?</div>
<div id="d8" class="dice" value="8">?</div>
JS
$(document).ready(function() {
$('.dice').click(function() {
var currentDice = $(this).val();
console.log(currentDice);
});
});
Upvotes: 0
Views: 51
Reputation: 67525
value
isn't a div
attribute so I suggest the use of data-*
attributes instead when you want to add costum attribute, like :
<div id="d4" class="dice" data-value="4">?</div>
Then in your js use the jQuery method .data()
:
$(this).data('value');
Hope this helps.
$(function() {
$('.dice').on('click', function() {
console.log($(this).data('value'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="d4" class="dice" data-value="4">?</div>
<div id="d6" class="dice" data-value="6">?</div>
<div id="d8" class="dice" data-value="8">?</div>
Upvotes: 0
Reputation: 55
try with:
$('.dice').click(function() {
var currentDice = $(this).attr('value');
console.log(currentDice);
});
Upvotes: 1
Reputation: 53228
value
is not a valid attribute for <div>
elements (please see spec). Don't clutter up the DOM with invalid attributes, use data-
instead:
<div id="d4" class="dice" data-value="4">?</div>
<div id="d6" class="dice" data-value="6">?</div>
<div id="d8" class="dice" data-value="8">?</div>
jQuery's val()
function is not a drop-in for attr()
or similar. If you update your markup to use data-
attributes, you can then use jQuery's data()
function as follows:
$(function() {
$('.dice').click(function() {
var currentDice = $(this).data('value');
console.log(currentDice);
});
});
Upvotes: 0
Reputation: 182
You should use "attr"
$(document).ready(function() {
$('.dice').click(function() {
var currentDice = $(this).attr("value");
console.log(currentDice);
});
});
Upvotes: 1
Reputation: 18908
.val()
is used for form elements (input, select, etc), that actually have a true name value pair associated. Because you are using a div, you should be getting the attribute of value (.attr('value')
):
That being said, and while that works, you really should use the data-
attribute for custom attributes on elements (ex: data-value="4"
):
$(document).ready(function() {
$('.dice').click(function() {
var currentDice = $(this).attr('data-value');
console.log(currentDice);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="d4" class="dice" data-value="4">?</div>
<div id="d6" class="dice" data-value="6">?</div>
<div id="d8" class="dice" data-value="8">?</div>
Upvotes: 1