Skip to content
Advertisement

Page refreshes after I hit the button

It’s a simple counting vowels page. When I insert a word WITH vowels, the result shows up for a second and then page refreshes. When there are no vowels, the output is not as expected and then the page refreshes again. Could anyone help me out please?

function findVow(event) {
  event.preventDefault();
  var input, result;
  // Get value of the input
  input = document.getElementById('text').value;
  var regex = /[aeiou]/gi;
  //unify the case and get the length
  var count = input.match(regex).length;

  if (count > 0) {
    result = "Vowels found : " + count;
  } else {
    result = "No vowels found";
  }
  //print the number of vowels if any
  document.getElementById("demo").innerHTML = result;
};
<!DOCTYPE html>
<html>

<head>
  <title>challenge1</title>
</head>

<body>
  <form>
    <input id="text" placeholder="Enter a word" type="text" />
    <br><br>
    <button onclick="findVow()">Count vowels</button>
    <br>
    <p id="demo"></p>
  </form>
  <script type="text/javascript" src="script.js"></script>
</body>

</html>

Advertisement

Answer

You are submitting the form when using default buttons.

The event you wanted is not passed as you expect – it is the button that is passed.

EITHER use type=button OR better: use event.preventDefault as now, but on the submit event

document.getElementById("myForm").addEventListener("submit", function(event) {
  event.preventDefault();
  var input, result;
  // Get value of the input
  input = document.getElementById('text').value;
  var regex = /[aeiou]/gi;
  //unify the case and get the length
  var count = input.match(regex).length;

  if (count > 0) {
    result = "Vowels found : " + count;
  } else {
    result = "No vowels found";
  }
  //print the number of vowels if any
  document.getElementById("demo").innerHTML = result;
});
<form id="myForm">
  <input id="text" placeholder="Enter a word" type="text" />
  <br><br>
  <button>Count vowels</button>
  <br>
</form>
<p id="demo"></p>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement