Add two eventlisteners to two submit buttons in one form

Viewed 974

I have one form with 2 submit buttons, and for each one I want to add a different event listener on click, and perform a different action for each one. But the second one is not working, the function does not fire. I am new on JS so any help will be welcome. Thanks in advance. My code is: HTML

<form id="searching" action="javascript:void(0);">
              <input class="form-class w-50" type="text" id="search" placeholder="Input your search keyword" name="search">
              <br><br>
              <input type="submit" class="btn btn-warning" id="submit" value="Weather" name="weather">
              <input type="submit" class="btn btn-warning" id="submit2" value="Forecast!" name="forecast">
</form>

JS

const submit = document.getElementById('submit');
submit.addEventListener('click', event.getSearch.bind(this,'search'));

const submit2 = document.getElementById('submit2');
submit2.addEventListener('click', event.getForecast.bind(this));
1 Answers

The behavior you specify works fine in principle, so it may just be a matter of making sure the function you want to call is actually being called (and called in the appropriate context.)

(Since you're calling custom functions instead of actually submitting the form, you could also consider changing the submit inputs to normal buttons, and possibly even omitting the form element entirely.)

const
  submit = document.getElementById('submit'),
  submit2 = document.getElementById('submit2');
submit.addEventListener('click', getSearch);
submit2.addEventListener('click', getForecast);

function getSearch(){ console.log("searching..."); }
function getForecast(){ console.log("forecasting..."); }
<form id="searching" action="javascript:void(0);">
  <label for="search">Search </label><input id="search"/><br><br>
  <input type="submit" id="submit" value="Weather"/>
  <input type="submit" id="submit2" value="Forecast!"/>
</form>

Related