Reputation: 1209
I am working with Jquery and php,I have text box and i am trying to pass "data attribute" (data-vals) value using jquery but i am getting "undefined" as response, Here is my code,Where i am wrong ?
<input type='text' name='postcmnt' class='postcmnt' value='" + str + "' data-vals='123' onkeydown='search(this)' />
<script>
function search(ele) {
if(event.key === 'Enter') {
var valss=$(this).data('vals');
alert('attribute value is '+valss);
}
}
</script>
Upvotes: 0
Views: 200
Reputation: 5344
You can also try this -
<input type='text' name='postcmnt' class='postcmnt' value='' data-id="123" onkeydown="search(this)" />
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function search(ele) {
if(event.key === 'Enter') {
console.log(ele.getAttribute("data-id"));
}
}
</script>
Upvotes: 1
Reputation: 5322
Simply you can use on
keypress
with class
postcmnt
or with input
$('.postcmnt').on('keypress', function(e) {
var code = e.keyCode || e.which;
var _t = $(this);
if(code==13){
var valss=_t.data('vals');
var inputVal=_t.val();
alert('attribute value is '+valss);
alert('input value is '+inputVal);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' name='postcmnt' class='postcmnt' value='abc' data-vals='123'/>
Upvotes: 1