pythag0ras_
pythag0ras_

Reputation: 162

jQuery $('input :selected').val() returns undefined

I know this is probably a stupid question, but I can't find the answer anywhere.

When I try to run this code:

$(() => {
    $("input.search").on('keyup', () => {
        console.log($("input.search :selected").val());
    });
});
<head>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js'
        integrity='sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg=='
        crossorigin='anonymous'></script>
</head>
<body>
  <form class="search">
      <input type="text" class="search" placeholder="Search..." name="search">
  </form>
</body>
The line $("input.search :selected").val() returns null. Why is this, and how do I fix it? Thanks so much!

Upvotes: 0

Views: 55

Answers (1)

brk
brk

Reputation: 50346

According to selected-selector selected works with options. In your case you could have used $(this) but since you are using fat function the scope of this will be different So use the event object to get the value

$(() => {
  $("input.search").on('keyup', (e) => {
    console.log(e.target.value);
  });
});
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js' integrity='sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==' crossorigin='anonymous'></script>
</head>

<body>
  <form class="search">
    <input type="text" class="search" placeholder="Search..." name="search">
  </form>

Upvotes: 2

Related Questions