Vladimir Jovanović
Vladimir Jovanović

Reputation: 5561

Input value sometimes doesn't apply

To be straightforward, on a page, there is a search input.

var input = document.getElementById('search-input');

function handle(e) {
  if (e.keyCode === 13) {
    window.location = '../?s=' + input.value;
  }
}
<div class="search-form-mobile">
  <input type="text" id="search-input" onkeypress="handle(event)" class="form-control" placeholder="Search">
</div>

I know that this is a correct JavaScript code, but my question is, why does it sometimes accepts the input value and sometimes it doesn't? I've been scratching my head for a while and can't figure out what's wrong.

Should I wrap it up in a <form> or can i leave it like that?

The <script> is at the very bottom in footer.php.

It's a WordPress site.

Upvotes: 0

Views: 76

Answers (1)

tao
tao

Reputation: 90208

Use onkeydown (or onkeyup, if you want the event to fire when the key is released, not when pressed) instead of onkeypress.

You can find a full list of keys that fire onkeypress event here.


Following the comments, it looks like this is not a JavaScript issue at all, but has to do with escaping the query string, specifically about what characters you can and cannot use without escaping in a $_GET parameter.

This has been asked and answered before.

Upvotes: 1

Related Questions