Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i set value attribute to a div tag?

Tags:

jquery

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);
});
like image 714
lys916 Avatar asked Mar 19 '16 00:03

lys916


People also ask

How do you add a value to a div in HTML?

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.

Can div have value HTML?

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.


2 Answers

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);
});
like image 102
charlietfl Avatar answered Sep 21 '22 19:09

charlietfl


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);
});
like image 31
Renuka Deshmukh Avatar answered Sep 20 '22 19:09

Renuka Deshmukh