why does input.value is returning undefined when call it in alert

Viewed 195

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

4 Answers

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()

in jquery you should use .val() to get the value of the field insted of .value

`const food = $('#food').val();`
Related