I have a simple JavaScript code to add a string into a ul list:
function init() {
var button = document.getElementById("addButton");
button.onclick = handleButtonClick;
}
function handleButtonClick() {
var textInput = document.getElementById("songTextInput");
var songName = textInput.value;
if (songName == "") {
alert("Please enter a song");
} else {
//alert("Adding song " + songName);
var li = document.createElement("li");
li.innerHTML = songName;
var ul = document.getElementById("playlist");
ul.appendChild(li);
}
}
HTML:
<form>
<input type="text" id="songTextInput" size="40" placeholder="Song name">
<input type="button" id="addButton" value="Add Song">
</form>
<ul id="playlist">
</ul>
The problem is: when I set my input element as type="button"
, this JavaScript works, but when I set it as type="submit"
, it runs well until the first condition or with the alert of second condition, but it doesn't add the song to the list. Why does this occur?