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?
JavaScript
x
17
17
1
function findVow(event) {
2
event.preventDefault();
3
var input, result;
4
// Get value of the input
5
input = document.getElementById('text').value;
6
var regex = /[aeiou]/gi;
7
//unify the case and get the length
8
var count = input.match(regex).length;
9
10
if (count > 0) {
11
result = "Vowels found : " + count;
12
} else {
13
result = "No vowels found";
14
}
15
//print the number of vowels if any
16
document.getElementById("demo").innerHTML = result;
17
};
JavaScript
1
19
19
1
<!DOCTYPE html>
2
<html>
3
4
<head>
5
<title>challenge1</title>
6
</head>
7
8
<body>
9
<form>
10
<input id="text" placeholder="Enter a word" type="text" />
11
<br><br>
12
<button onclick="findVow()">Count vowels</button>
13
<br>
14
<p id="demo"></p>
15
</form>
16
<script type="text/javascript" src="script.js"></script>
17
</body>
18
19
</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
JavaScript
1
17
17
1
document.getElementById("myForm").addEventListener("submit", function(event) {
2
event.preventDefault();
3
var input, result;
4
// Get value of the input
5
input = document.getElementById('text').value;
6
var regex = /[aeiou]/gi;
7
//unify the case and get the length
8
var count = input.match(regex).length;
9
10
if (count > 0) {
11
result = "Vowels found : " + count;
12
} else {
13
result = "No vowels found";
14
}
15
//print the number of vowels if any
16
document.getElementById("demo").innerHTML = result;
17
});
JavaScript
1
7
1
<form id="myForm">
2
<input id="text" placeholder="Enter a word" type="text" />
3
<br><br>
4
<button>Count vowels</button>
5
<br>
6
</form>
7
<p id="demo"></p>