gabor aron gabor aron - 2 months ago 23
Javascript Question

form javascript submit event

I want to manage a form only with javascript, but the eventlistener doesn't worked for me. What's wrong?

My form:

<script src="init.js"></script>
<div id="search_box">
<form id="search_form">
<input type="search" name="search" autofocus placeholder="Google search" id="searchbox">
<input type="button" value=&#9679; id="searchsign">
</form>
</div>
<script src="search.js"></script>


In init.js file:

"use strict";

function $(selector){
return document.querySelector(selector);
}

function $$(selector){
return document.querySelectorAll(selector);
}


in search.js file:

$('#searchsign').addEventListener('click', search);
$('#search_form').addEventListener('submit', search);

function search(){
console.info('search function OK');
var searchvalue = $("#searchbox").value;
var google = "https://www.google.hu/search?site=&source=hp&q=";
window.location = google + searchvalue;
}

Answer

The form's submit event will go to the form's action (no action = the current URL) and reload the page.

If you're handling it with JavaScript, accept the event argument and call preventDefault on it to prevent the default behavior:

function search(e) {
    e.preventDefault();
    // ...
}

I would also suggest either not making your functions globals, or giving search a different name to avoid conflicts in the global namespace.


Side note: You need to URI-encode query string arguments, so change your location assignment to use encodeURIComponent:

window.location = google + encodeURIComponent(searchvalue);

Working copy on JSBin (Since Stack Snippets work in frames that don't allow us to move off to Google)

Source of working example:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div id="search_box">
  <form id="search_form">
    <input type="search" name="search" autofocus placeholder="Google search" id="searchbox">
    <input type="button" value=&#9679; id="searchsign">
  </form>
</div>
<script>
"use strict";
(function() { // Scoping function to avoid globals
  function $(selector) {
    return document.querySelector(selector);
  }

  function $$(selector) {
    return document.querySelectorAll(selector);
  }

  $('#searchsign').addEventListener('click', search);
  $('#search_form').addEventListener('submit', search);

  function search(e) {
    e.preventDefault();
    console.info('search function OK');
    var searchvalue = $("#searchbox").value;
    var google = "https://www.google.hu/search?site=&source=hp&q=";
    window.location = google + encodeURIComponent(searchvalue);
  }
})();
</script>
</body>
</html>