0

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>
2
  • Can you post the output of "console.log(ele)" Commented Jan 27, 2022 at 4:57
  • @SachinVairagi: i am getting following value "[object HTMLInputElement]" Commented Jan 27, 2022 at 5:00

2 Answers 2

1

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'/>

Sign up to request clarification or add additional context in comments.

2 Comments

But how can i get current texbox value ( which i entered) ?
@Nisha check it now.
1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.