What are the differences between "type = button" and "type = submit" in an input?

5
I have a simple JavaScript code to add a string to a ul list:

JS:

function init() {
    var botao = document.getElementById("addButton");
    botao.onclick = handleButtonClick;
}

function handleButtonClick() {
    var textInput = document.getElementById("songTextInput");
    var songName = textInput.value;
    if (songName == "") {
        alert("Por favor, adicione um pergunta");
    } else {
       //alert("Adicionando a música " + 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="Nome da música">
    <input type="button" id="addButton" value="Adicionar música">
</form>
<ul id="playlist">
</ul>

The problem is: When I define my input with type=button , this javascript works, but when I set it to type=submit , it runs legal until the first condition or with the second alert condition, but does not add the string in the list.

Does anyone know why this happens?

    
asked by anonymous 20.08.2015 / 21:50

2 answers

4

The type='submit' has a special behavior, when pressed the form will be sent - unless you prevent it with Javascript. Since type='button' , as the type suggests is only a button that by default has no functionality - which you can add with some script .

The problem with your code is that the function init - responsible for assigning the click event to the button - is never executed, so when the button is pressed it maintains its default functionality : Do nothing.

function init() {
  var botao = document.getElementById("addButton");
  botao.onclick = handleButtonClick;
}

function handleButtonClick() {
  var textInput = document.getElementById("songTextInput");
  var songName = textInput.value;
  if (songName == "") {
    alert("Por favor, adicione um pergunta");
  } else {
    //alert("Adicionando a música " + SongName);
    var li = document.createElement("li");
    li.innerHTML = songName;
    var ul = document.getElementById("playlist");
    ul.appendChild(li);
  }
}


// chamando init :)
init();
<form>
  <input type="text" id="songTextInput" size="40" placeholder="Nome da música">
  <input type="button" id="addButton" value="Adicionar música">
</form>
<ul id="playlist">
</ul>
    
20.08.2015 / 23:59
1

In your form it's missing to run the submit

<form onSubmit="return false;">

</form>

In the form tag there is a built-in listener onSubmit, when you put the submit button, auto implements the submit on that button, it is necessary to enter a return false to lock the submit and do the checks.

    
25.09.2015 / 22:52