I have a text input and I want to alert the input.value after press enter
so I have made this code HTML :
<input type="text" id="food">
js :
$('#food').on('keypress',function(e) {
if(e.which == 13) {
const food = $('#food').value;
alert(food);
}
});
in the alert, it's showing undefined.
in addition, there is no console error in the console
You should use val() method to get the value of the input in jquery
$('#food').val()
value is used in vanilla JS, not in jquery.
$('#food').on('keypress', function(e) {
if (e.which == 13) {
const food = $('#food').val();
console.log(food);
// alert( food );
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="food">
You need to use a function on jQuery to get that value.
$('#food').val();
$('#food').attr('value');
It is not const food = $("#food").value but const food = $("#food").val()