In my current project, I have a html form which contain a structure like that:
<!-- Tab links -->
<div class="tab_idioma">
<button class="tabidioma active" id="en-US-tab" onclick="openIdiomaTab(this);" data-id="en-US">en-US</button>
<button class="tabidioma" id="es-ES-tab" onclick="openIdiomaTab(this);" data-id="es-ES">es-ES</button>
<button class="tabidioma" id="pt-BR-tab" onclick="openIdiomaTab(this);" data-id="pt-BR">pt-BR</button>
</div>
<!-- Tab content -->
<div id="en-US" class="tabcontent_idioma" style="display: block;">
...
</div>
<div id="es-ES" class="tabcontent_idioma" style="display: block;">
...
</div>
<div id="pt-BR" class="tabcontent_idioma" style="display: block;">
...
</div>
What’s happening is that when I try access the second (or third tab) the form is submitted to the server, before I fil all the fields of the form, persisting incomplete data on the database.
the javascript function which should be called is:
function openIdiomaTab(element) {
// Declare all variables
var id = element.dataset.id;
var i, tabcontent, tablinks;
// Get all elements with class="tabcontent" and hide them
tabcontent = document.getElementsByClassName("tabcontent_idioma");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// Get all elements with class="tablinks" and remove the class "active"
tablinks = document.getElementsByClassName("tabidioma");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(id).style.display = "block";
document.getElementById(id+'-tab').className += " active";
}
the submission process should be handled by this function:
function submit_insert() {
var formData = new FormData(document.getElementById("form"));
var url = document.getElementById("form").action;
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.onload = function(event) {
event.preventDefault();
document.getElementById('insert').innerHTML = '';
document.getElementById('table-body').innerHTML = '';
openTab('listagem-tab', 'listagem');
load_content();
};
xhr.send(formData);
}
But this is not happening for this undesired submission. Anyone can give a hint of what is happening here?
Advertisement
Answer
The default type for a button is submit. If you are using a button inside of a form for a different reason, you need to explicitly set the type to button so it won’t submit the form:
<button type='button'....>