I’m studying how to work with HTML forms and JavaScript (JS) and I faced a problem:
I wrote the Meta tags (HTML) and used JS elements, events and functions to treat possible user mistakes. The page shows when user follow in mistake and don’t insert the correct information. But, even with these mistakes, when the “submit button” is used, the alert message is not showing. I tried to inspect what’s happening and browser give a message like:
“DevTools failed to load source map: Could not load content for chrome-extension://nllcnknpjnininklegdoijpljgdjkijc/bundles/content.js.map: System error: net::ERR_BLOCKED_BY_CLIENT”.
Here is my code:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2>HTML Forms</h2>
<form id="formulario" action="">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="">
<span id="msg-vld-fname" style="color: red; display:none;"></span>
<br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="">
<span id="msg-vld-lname" style="color: red; display:none;"></span>
<br><br>
<label for="lgenre">Genre:</label><br>
<select name="lgenre" id="lgenre">
<option value="select">Select</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<span id="msg-vld-lgenre" style="color: red; display:none;"></span>
<br><br>
<input type="submit" value="Submit">
</form>
<script src="./index.js"></script>
</body>
</html>
JavaScript
`
//selecionar elementos - aqui entra tudo o que vai ser "mexido", "manipulável"
let form = document.getElementById("formulario");
let fname = document.getElementById("fname");
let lname = document.getElementById("lname");
let lgenre = document.getElementById("lgenre");
let fname_msg = document.getElementById("msg-vld-fname");
let lname_msg = document.getElementById("msg-vld-lname");
let lgenre_msg = document.getElementById("msg-vld-lgenre");
//validar quando usuário sai do campo
fname.onblur = function (event) {
if (event.target.value.length < 3) {
fname_msg.textContent = "Insert at least 3 carachters"; //exibe a mensagem
fname_msg.style.display = 'block'; //exibe um valor na tela
} else {
fname_msg.style.display = 'none'; //faz o valor da tela "sumir".
}
}
//validar quando usuário muda um campo
lgenre.onchange = function (event) {
if (event.target.value == "select") {
lgenre_msg.textContent = "Select a valida atribute."; //exibe a mensagem
lgenre_msg.style.display = 'block'; //exibe um valor na tela
} else {
lgenre_msg.style.display = 'none'; //faz o valor da tela "sumir".
}
}
//validar quando usuário entra em um campo
fname.onfocus = function () {
fname_msg.style.display = 'none';
}
//validar quando usuário envia o formulário
form.onsubimit = function (event){
if (fname.value.length < 3
|| lgenre.value == "selecione") {
alert("please, complete this form correctly after submition");
event.preventDefault();
}
}
`
My expactation is: when the form has mistakes, according to the rules, shows the alert and forbiden the submitoin.
First, you wrote your event property incorrectly as: **onsubimit** instead of **onsubmit**.
But, you are using a submit button, which attempts to send the form data to whatever resource the form element's action attribute is set to and it will attempt to redirect the browser to that location. In your case, you're not submitting data anywhere, so you should be using a regular button with a click event handler.
Also, you really should be using the modern standard for setting up event handlers, which is .addEventListener() instead of event properties like onXyz. See the updated code for the button's click event below.
And the 6 heading elements in HTML (h1...h6) should not be used because of the way they style their text. They are for setting up the structure of the document. As such, you should always start with h1 and then only use h2 if you want to create a sub-section of the h1. If you then don't like the style of the text that the heading element produces, use CSS to modify that instead of changing to a heading style that you like to the look of.
//selecionar elementos - aqui entra tudo o que vai ser "mexido", "manipulável"
// You don't need a reference to the form, you need a reference to the button
let button = document.querySelector("input[type='button']");
let fname = document.getElementById("fname");
let lname = document.getElementById("lname");
let lgenre = document.getElementById("lgenre");
let fname_msg = document.getElementById("msg-vld-fname");
let lname_msg = document.getElementById("msg-vld-lname");
let lgenre_msg = document.getElementById("msg-vld-lgenre");
//validar quando usuário envia o formulário
// You should just use a regular button and set up a click event handler for it
// using the modern, standards-based approach of .addEventListener()
button.addEventListener("click", function (event){
if (fname.value.length < 3
|| lgenre.value == "selecione") {
alert("please, complete this form correctly after submition");
event.preventDefault();
}
});
//validar quando usuário sai do campo
fname.onblur = function (event) {
if (event.target.value.length < 3) {
fname_msg.textContent = "Insert at least 3 carachters"; //exibe a mensagem
fname_msg.style.display = 'block'; //exibe um valor na tela
} else {
fname_msg.style.display = 'none'; //faz o valor da tela "sumir".
}
}
//validar quando usuário muda um campo
lgenre.onchange = function (event) {
if (event.target.value == "select") {
lgenre_msg.textContent = "Select a valida atribute."; //exibe a mensagem
lgenre_msg.style.display = 'block'; //exibe um valor na tela
} else {
lgenre_msg.style.display = 'none'; //faz o valor da tela "sumir".
}
}
//validar quando usuário entra em um campo
fname.onfocus = function () {
fname_msg.style.display = 'none';
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>HTML Forms</h1>
<form id="formulario" action="">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="">
<span id="msg-vld-fname" style="color: red; display:none;"></span>
<br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="">
<span id="msg-vld-lname" style="color: red; display:none;"></span>
<br><br>
<label for="lgenre">Genre:</label><br>
<select name="lgenre" id="lgenre">
<option value="select">Select</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<span id="msg-vld-lgenre" style="color: red; display:none;"></span>
<br><br>
<input type="button" value="Submit">
</form>
<script src="./index.js"></script>
</body>
</html>
Related
"use strict";
let btn = document.getElementById("buttonCarrito");
btn.addEventListener("click",agregar);
//this function is agregar (add in English), the idea is that this function put the elements Manzana (Apple) in the shop cart but when i try do this i get [object HTMLSpanElement]50 (50 is the Apple value, but i don't can show only the number 50)
function agregar(){
let Productos= {
"Manzana": "50",
"Banana": "40",
"Naranja": "30",
"Mandarina": "20"
}
console.table(Productos)
let frutaComprada= document.getElementById("inputProducto").value;
let costoTotal= document.getElementById("valor");
let productoSeleccionado=Productos[frutaComprada];
costoTotal=costoTotal+productoSeleccionado;
valor.innerHTML=costoTotal;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container">
<h1>Bienvenido a la tienda</h1>
<input id="inputProducto" type="text" placeholder="Ingrese su producto">
<br>
<br>
<input id="inputCompra" type="text" placeholder="Ingrese el valor de su compra">
<br>
<br>
<button id="buttonCarrito">Agregar al carrito</button>
<p>El valor total de su compra es: <span id="valor"> 0 </span></p>
</div>
</body>
<script src="js.js"></script>
</html>
Values from form inputs will always be strings, so to add numbers together you need to coerce the string to a number. A couple of methods: 1) Number(str) or 2) +str.
Your object of products/prices: there's no need to have those prices as strings.
The main problem you were having is that let costoTotal= document.getElementById("valor"); is only picking up the element and not the text content. We can use let costoTotal= document.getElementById("valor").textContent; for that, but then we need to coerce that to a number similarly to input values.
(Sidenote: at the moment your code doesn't use the value from inputCompra which is why I asked about it in the comments. So the total will increase by 40 for bananas, for example, regardless of what is entered in that input.)
let btn = document.getElementById("buttonCarrito");
btn.addEventListener("click", agregar);
function agregar() {
let Productos = {
Manzana: 50,
Banana: 40,
Naranja: 30,
Mandarina: 20
}
let frutaComprada = document.getElementById("inputProducto").value;
let costoTotal = Number(document.getElementById("valor").textContent);
let productoSeleccionado = Productos[frutaComprada];
costoTotal = costoTotal + productoSeleccionado;
valor.textContent = costoTotal;
}
<div class="container">
<h1>Bienvenido a la tienda</h1>
<input id="inputProducto" type="text" placeholder="Ingrese su producto">
<br>
<br>
<input id="inputCompra" type="text" placeholder="Ingrese el número de artículos">
<br>
<br>
<button id="buttonCarrito">Agregar al carrito</button>
<p>El valor total de su compra es: <span id="valor"> 0 </span></p>
</div>
Here's a version that uses quantity in case you were curious.
let Productos = {
Manzana: 50,
Banana: 40,
Naranja: 30,
Mandarina: 20
}
const product = document.getElementById('inputProducto');
const quantity = document.getElementById('inputCompra')
const valor = document.getElementById('valor');
const btn = document.getElementById('buttonCarrito');
btn.addEventListener('click', agregar);
function agregar() {
const frutaComprada = product.value;
const itemQuantity = Number(quantity.value);
const productoSeleccionado = Productos[frutaComprada];
const subTotal = productoSeleccionado * itemQuantity;
let costoTotal = Number(valor.textContent);
costoTotal = costoTotal + subTotal;
valor.textContent = costoTotal;
}
<div class="container">
<h1>Bienvenido a la tienda</h1>
<input id="inputProducto" type="text" placeholder="Ingrese su producto">
<br>
<br>
<input id="inputCompra" type="text" placeholder="Ingrese el valor de su compra">
<br>
<br>
<button id="buttonCarrito">Agregar al carrito</button>
<p>El valor total de su compra es: <span id="valor"> 0 </span></p>
</div>
Today I have a tricky (for me at least) question. There is a bug in my code, I don't know how to eliminate it. Basically I'm creating a simple Form in JavaScript as an homework, and I encountered this problem.
I have to enter my age in this form, and for now it's all ok. But I have to enter it twice: one with an <input> tag and one with a popup window. I can input the value in the <input> tag just fine, but when I'm trying to input the value by the prompt(), it "resets" the script, so I lose the value in the <input> object.
I need a way to store these information somewhere, or stop the prompt() from deleting these values or resetting the page.
<html lang="en">
<head>
<title>Document</title>
<style>
* {margin: 0; padding: 0;}
body {padding: 20px;}
</style>
<script>
var eta_btn;
function eta_controllo(eta_btn) {
eta_btn = Number(prompt("Inserisci la tua età"));
console.log(eta_btn);
}
function profession() {
var temp = document.getElementById("select").selectedIndex;
if (temp == 0) {
document.getElementById("lavoratore_txt").style.display = "";
document.getElementById("studente_txt").style.display = "none";
} else if (temp == 1) {
document.getElementById("studente_txt").style.display = "";
document.getElementById("lavoratore_txt").style.display = "none";
} else {
document.getElementById("studente_txt").style.display = "none";
document.getElementById("lavoratore_txt").style.display = "none";
}
}
function send_to_server() {
if (!(eta_btn == document.getElementById("età").value)) {
alert("Le due età inserite non sono concordi");
return false;
}
else if (eta_btn == document.getElementById("età").value && eta_btn < 14) {
alert("Hai meno di 14 anni!");
return false;
} else if (confirm("Sicuro di aver scelto la provincia " + document.querySelector('input[name="città"]:checked').value))
alert("Dati inviati correttamente");
else {
alert("Errore");
return false;
}
}
</script>
</head>
<body>
<form action="">
<p>NOME</p>
<input placeholder="scrivi qui il tuo nome" type="text"><br><br>
<p>PASSWORD</p>
<input placeholder="scrivi qui la tua password" type="text"><br><br>
<p>ETA'</p>
<input placeholder="scrivi qui la tua età" type="text" id="età">
<button onclick="eta_controllo()">CONTROLLO</button><br><br>
<input name="città" type="radio">GENOVA<br>
<input name="città" type="radio">SAVONA<br>
<input name="città" type="radio">IMPERIA<br>
<input name="città" type="radio">LA SPEZIA<br><br>
<select name="" id="select" onchange="profession()">
<option value="lavoratore">Lavoratore</option>
<option value="studente">Studente</option>
<option value="disoccupato">Disoccupato</option>
</select>
<p id="studente_txt" style="display: none">Vai a studiare!</p><br>
<textarea id="lavoratore_txt" style="display: none;" name="" id="" cols="30" rows="10"></textarea><br><br>
<button>ANNULLA TUTTO</button>
<button onclick="send_to_server()">INVIA AL SERVER</button>
</form>
</body>
</html>
All you have to do is to add type="button" to the button.
The default type of button is "submit", so when you click it, it will submit the form.
Hi have you already taken a look at this link?
It could be ulile in my opinion ..
there are no global variables to manage the memories ..
The Localstorage of the browser.
I hope I have been of help .. good studyhttps://www.w3schools.com/jsref/prop_win_localstorage.asp
The "if (numero.value.length == 0)" works, but when I add a number the program doesn't work, the "Inspect" function (Ctrl + Shift + I) doesn't work and the page does not refresh.
function tabuada() {
var numero = document.getElementById('txtnum')
var tabuada = document.getElementById("selectTab")
if (numero.value.length == 0) {
window.alert("Você precisa digitar um número para que a tabuada seja gerada.")
} else {
var num = Number(numero.value)
tabuada.innerHTML = ""
for (c = 0; c = 10; c++) {
var item = document.createElement('option')
item.text = `${num} * ${c} = ${c * num}`
tabuada.appendChild(item)
}
}
}
<section>
<div>
<p>
Escolha um número: <input type="number" name="num" id="txtnum">
<input type="button" value="Gerar Tabuada" onclick="tabuada()">
</p>
</div>
<div>
<select name="tabuada" id="selectTab" size="10"></select>
</div>
</section>
You had to look more on your code:
Every opnening tag needs a closing one. /BODY and /HTML was missing.
Every line in Javascript needs a ; at the end.
The condition of your for-loop was wrong. You made an allocation c = 10 (which is allways true, so you have an infinite loop). If you want to compare something on equal use === or ==. But you had to compare for c < 10. The loop will as long iterate as your condition is true so smaller than is the choice.
Your function needs a closing }.
function tabuada() {
var numero = document.getElementById('txtnum');
var tabuada = document.getElementById("selectTab");
if (numero.value.length == 0) {
window.alert("Você precisa digitar um número para que a tabuada seja gerada.");
} else {
var num = Number(numero.value);
tabuada.innerHTML = "";
for (c = 0; c < 10; c++) {
var item = document.createElement('option');
item.text = `${num} * ${c} = ${c * num}`;
tabuada.appendChild(item);
}
}
}
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tabuada</title>
<link rel="stylesheet" href="_estiloEx16.css">
</head>
<body>
<header>
<h1>Tabuada</h1>
</header>
<section>
<div>
<p>
Escolha um número: <input type="number" name="num" id="txtnum">
<input type="button" value="Gerar Tabuada" onclick="tabuada()">
</p>
</div>
<div>
<select name="tabuada" id="selectTab" size="10"></select>
</div>
</section>
<footer>
<p>© Curso em vídeo</p>
</footer>
</body>
</html>
It seems that my "validate" function is not activating for some reason.
I've tried by to use onsubmit and onclick, as well as tried to use ID in the place of name.
The script is already preloaded on head.
function validar() {
var nome = formulario.nome.value;
var email = formulario.email.value;
var cpf = formulario.cpf.value;
var telefone_fixo = formulario.telefone_fixoe.value;
var telefone_celular = formulario.telefone_celular.value;
var login = formulario.login.value;
var senha = formulario.senha.value;
var rep_senha = formulario.rep_senha.value;
if (nome == "") {
alert("Preencha o campo com seu NOME");
formulario.nome.focus();
return false;
}
if (nome.lenght < 5) {
alert("Digite seu NOME COMPLETO");
formulario.nome.focus();
return false;
}
if (cpf.lenght < 11) {
alert("Digite apenas os números do CPF");
formulario.cpf.focus();
return false;
}
if (telefone_fixo < 10) {
alert("Digite apenas os números do TELEFONE");
formulario.telefone_fixo.focus();
return false;
}
if (telefone_celular < 11) {
alert("Digite apenas os números do CELULAR");
formulario.telefone_celular.focus();
return false;
}
if (senha != rep_senha) {
alert("SENHAS não são iguais");
return false;
}
}
<form id="formulario">
<div>PREENCHA OS CAMPOS COM SEUS DADOS REAIS:</div><br/> Nome:
<br/>
<input type="text" id="nome" name="nome"><br/><br/> Email:
<br/>
<input type="text" id="email" name="email" placeholder="exemplo#exemplo.com"><br/><br/> CPF:
<font size="1">(Digite apenas números)</font><br/>
<!--Função de CSS invadindo o HTML provisoriamente-->
<input type="text" id="cpf" name="cpf" placeholder="000.000.000-00"><br/><br/> Telefone:
<font size="1">(Digite apenas números)</font><br/>
<!--Função de CSS invadindo o HTML provisoriamente²-->
<input type="text" id="telefone_fixo" name="telefone_fixo" placeholder="(00) 0000-0000"><br/><br/> Celular:
<font size="1">(Digite apenas números)</font><br/>
<!--Função de CSS invadindo o HTML provisoriamente³-->
<input type="text" id="telefone_celular" name="telefone_celular" placeholder="(00) 00000-0000"><br/><br/><br/>
<div>ESCOLHA SEU LOGIN E SUA SENHA:</div><br/> Login:
<br/>
<input type="text" id="login" name="login"><br/><br/> Senha:
<br/>
<input type="password" id="senha" name="senha"><br/><br/> Repetir Senha:<br/>
<input type="password" id="rep_senha" name="rep_senha"><br/><br/><br/>
<input type="submit" value="Enviar" onclick="return validar()">
<input type="reset" value="Limpar" name="limpar">
</form>
misspelled length
misspelled fixo
missed .length on phone numbers
you need to attach to the submit handler and use preventDefault if error
function validar(e) {
var formulario = this;
var nome = formulario.nome.value;
var email = formulario.email.value;
var cpf = formulario.cpf.value;
var telefone_fixo = formulario.telefone_fixo.value;
var telefone_celular = formulario.telefone_celular.value;
var login = formulario.login.value;
var senha = formulario.senha.value;
var rep_senha = formulario.rep_senha.value;
var error = false
if (nome == "") {
alert("Preencha o campo com seu NOME");
formulario.nome.focus();
error = true;
}
if (!error && nome.lenght < 5) {
alert("Digite seu NOME COMPLETO");
formulario.nome.focus();
error = true;
}
if (!error && cpf.length < 11) {
alert("Digite apenas os números do CPF");
formulario.cpf.focus();
error = true;
}
if (!error && telefone_fixo.length < 10) {
alert("Digite apenas os números do TELEFONE");
formulario.telefone_fixo.focus();
error = true;
}
if (!error && telefone_celular.length < 11) {
alert("Digite apenas os números do CELULAR");
formulario.telefone_celular.focus();
error = true;
}
if (!error && senha != rep_senha) {
alert("SENHAS não são iguais");
error = true;
}
if (error) e.preventDefault();
}
window.addEventListener("load",function() {
document.getElementById("formulario").addEventListener("submit",validar);
})
<form id="formulario">
<div>PREENCHA OS CAMPOS COM SEUS DADOS REAIS:</div><br/> Nome:
<br/>
<input type="text" id="nome" name="nome"><br/><br/> Email:
<br/>
<input type="text" id="email" name="email" placeholder="exemplo#exemplo.com"><br/><br/> CPF:
<font size="1">(Digite apenas números)</font><br/>
<!--Função de CSS invadindo o HTML provisoriamente-->
<input type="text" id="cpf" name="cpf" placeholder="000.000.000-00"><br/><br/> Telefone:
<font size="1">(Digite apenas números)</font><br/>
<!--Função de CSS invadindo o HTML provisoriamente²-->
<input type="text" id="telefone_fixo" name="telefone_fixo" placeholder="(00) 0000-0000"><br/><br/> Celular:
<font size="1">(Digite apenas números)</font><br/>
<!--Função de CSS invadindo o HTML provisoriamente³-->
<input type="text" id="telefone_celular" name="telefone_celular" placeholder="(00) 00000-0000"><br/><br/><br/>
<div>ESCOLHA SEU LOGIN E SUA SENHA:</div><br/> Login:
<br/>
<input type="text" id="login" name="login"><br/><br/> Senha:
<br/>
<input type="password" id="senha" name="senha"><br/><br/> Repetir Senha:<br/>
<input type="password" id="rep_senha" name="rep_senha"><br/><br/><br/>
<input type="submit" value="Enviar">
<input type="reset" value="Limpar" name="limpar">
</form>
I have a dynamic html form that is created with a javascript file where i ask the user to enter the number of fields and the input name of the fields. I want to know if is possible to the user download the form created dynamically as html page. The website doesn't have a database.
This snippet demonstrates how i create a form dynamically, all of this is being done on the client side.
var Nome; // Nome do esquema
var Desc; // descrição do esquema
var temas = []; // Nome dos temas do form
var fields = []; // nr de campos
var FL= []; // Nome do campo
var FLT =["date","time","number","text"];
var TF =[]; // tipo do campo
var Asset;
var a=0;
function Temas(){
"use strict";
Nome= prompt("Qual o Nome do Esquema de Metadados?");
Desc = prompt("Introduza a Descrição do Esquema.");
Asset = prompt("Introduza o valor da TAG AssetSubtype.");
var nT=prompt("Quantos temas tem o formulário?");
if(nT === null || nT === "") {
alert("User cancelled the prompt.");
} else {
for (var i=0; i<nT; i++){
temas.push(prompt("Introduzir Tema"));
if(temas[i] === null || temas[i] === "") {
alert("User cancelled the prompt.");
}
fields.push(prompt("Quantos campos terá o " + (i+1) + "º tema ?"));
if(fields[i] === null || fields[i] === "") {
alert("User cancelled the prompt.");
}
var f = fields[i];
for( var k=0; k<f; k++){
FL.push(prompt("Qual é o Nome do " + (k+1) + "º campo?"));
if(FL[k] === null || FL[k] === "") {
alert("User cancelled the prompt.");
}
TF.push(prompt("Qual o tipo do " + (k+1) + "º campo? "+
"(Text | Number | Time | Date)"));
if(FL[k] === null || FL[k] === "") {
alert("User cancelled the prompt.");
}
if(TF[k] === FLT[0]) {
TF.push(FLT[0]);
}
if(TF[k] === FLT[1]) {
TF.push(FLT[1]);
}
if(TF[k] === FLT[2]) {
TF.push(FLT[2]);
}
if(TF[k] === FLT[3]) {
TF.push(FLT[3]);
}
}
}
}
alert("Bem sucedido");
}
// Função guardar nome e desc de esquema txt
/*function save(){
var blob = new Blob([Desc], {type: "text/plain;charset=utf-8"});
saveAs(blob, Nome+".txt");
} */
function gerar(){
"use strict";
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"");
f.setAttribute("class", "FormClass");
for(var l=0;l<temas.length; l++){
var div = document.createElement("div");
div.setAttribute('class', 'form');
div.setAttribute('id', "form"+(l+1));
var P = document.createElement('p'); // Heading of Form
P.innerHTML = temas[l];
div.appendChild(P);
for(var j=0;j<fields[l];j++){
var i = document.createElement("input");
i.setAttribute('name', FL[a+j]);
i.setAttribute('type', TF[a+j]);
i.setAttribute('placeholder', FL[a+j]);
div.appendChild(i);
}
a=a+parseInt(fields[l]);
if(l%2===0){
div.style.width='50%';
div.style.float='left';
} else{
div.style.width='48%';
div.style.float='right';
}
f.appendChild(div);
}
document.getElementById('form').appendChild(f);
}
<!DOCTYPE html>
<html><head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../CSS/form.css" >
</head>
<script src="../JS/FormDinamico.js"></script>
<script src="../JS/XML.js"></script>
<script src="../JS/XML-HTML.js"></script>
<script>
function Reset() {
document.getElementsById("1").reset();
}
</script>
<style>
button{
background-color: green;
margin-top: 10px;
margin-left: 11%;
border: 5px;
color: white;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
}
.main{
width:70%;
}
}</style>
<body>
<div id="main">
<button onclick="Temas();" id="gerar1">Criar</button>
<button onclick="gerar();" id="gerar">Gerar</button>
<div id="form">
<!--form here -->
<div id="form7">
<button class="button" type="button">Procurar XML</button>
<button class="button" type="button" name="btnSub" onclick="download(this.form)">Gerar XML</button>
<button class="button" type="button" value="Reset" onclick="Reset();">Reset</button>
<!-- <button class="button" type="button" onclick="download">Save</button> -->
</div>
</div>
</div>
</body>
</html>
You can load it on a new tab setting the headers (simply generate a DOM with proper headers to it and write as html) for it or with an html link (HTML5 only. server side lang needed to generate a file).
See:
https://www.designedbyaturtle.co.uk/2016/how-to-force-the-download-of-a-file-with-http-headers-and-php/
for further details.
You'll need to do one of this things:
1- write a file with dynamically generated content on the server to deliver it as a downloadable response (for example with php, c#, java or whatever server-side programing language your server admits).
2- Generate a printable document "on the fly" for example as .pdf (i didnt tryed with an html document but i suppose it's possible too) and set the headers to force the browser to interpret it as downloadable.
There's an example:
<html>
<head>
<title>
</title>
</head>
<body id="html-doc">
<br/>
<form id="main" method="post" action="main.php">
<label>surname: <input type="text" name="surname" /></label><br/><br/>
<label>Comment: <textarea id="text-val" rows="4"><strong>This is the</strong> content of my file</textarea></label><br/>
<input type="button" id="dwn-btn" value="submit"/>
<p></p>
<a onclick="this.href='data:text/html;charset=UTF-8,'+encodeURIComponent(document.documentElement.outerHTML)" href="#" download="page.html">Download all as HTML</a>
</form>
</body>
</html>
Edited to allow download the entire HTML code.