Reputation: 2564
<script>
$(document).ready(function(e) {
$('.btn').click(function(){
alert($(this).val());
});
});
</script>
<style>
.btn{width:20px; height:20px; background:red;}
</style>
<div class="btn" value="a"></div>
<div class="btn" value="b"></div>
<div class="btn" value="c"></div>
I have many div button use loop create from db.
im tring to detect the value of each button. so when user click, i can get the value from button.
My question is, is any way to set up the value into elements? or is any other options?
If i use input type hidden, its not visible, if i use input type button, the value of text will display.
Upvotes: 1
Views: 378
Reputation: 15609
If you want it with text, use
alert($(this).text());
If you want the value, use:
alert($(this).attr('value'));
If you give the div
a data-value='a'
then you can use
alert($(this).data('value'));
Upvotes: 1
Reputation: 943999
Div elements can't have values. Those are for form controls.
If you want to store arbitrary data in an attribute then use a data-
attribute.
<div class="btn" data-letter="a"></div>
and
alert($(this).data('letter'));
That said, if you want a button, then use a <button>
. Browsers know that they are interactive elements. They tell users that they are interactive elements. People can focus them. Screen readers will announce them. You can give their functionality a server side fallback.
<button value="a">What does this button do?</button>
Then you can use .val()
, since buttons are form controls.
Upvotes: 4
Reputation: 85575
use text instead
alert($(this).text());
val() is only for input elements
Upvotes: 0