I have 3 boxes, when i click on each box i want to alert the attribute value of each box.
https://jsfiddle.net/aedzgu9v/
<div class="box" value="box1"></div>
<div class="box" value="box2"></div>
<div class="box" value="box3"></div>
.box{
height: 80px;
width: 80px;
border: 2px solid blue;
margin: 5px;
}
$('.box').on('click', function(){
var value = $(this).val();
alert(value);
});
To append the data to <div> element we have to use DOM(Document Object Model) manipulation techniques. The approach is to create a empty <div> with an id inside the HTML skeleton. Then that id will be used to fetch that <div> and then we will manipulate the inner text of that div.
The HTML tags div and span hold no presentational value by themselves. This means that if you put then in your HTML, they will not actually display anything. These tags are primarily used as "hooks" for your CSS.
Only form controls have a legitimate property value
that allows you to use val()
... other elements do not
I suggest you switch to using a data-
attribute and access it using either data()
or attr()
<div class="box" data-value="box1"></div>
JS
$('.box').on('click', function(){
var value = $(this).data('value');
alert(value);
});
Try this instead:
<div class="box" name="box1"></div>
<div class="box" name="box2"></div>
<div class="box" name="box3"></div>
$('.box').on('click', function(){
var value = $(this).attr('name');
alert(value);
});
Or if you want to use value attribute:
$('.box').on('click', function(){
var value = $(this).attr('value');
alert(value);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With