How to save html form created dynamically using javascript - javascript

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.

Related

I can't see an alert advise

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>

"Inspect" function (Ctrl + Shift + I) doesn't work

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>

Javascript to jquery conversion

I'm trying to convert this javascript DOM into jquery, and my code isn't running for some reason. This is the DOM I am using.
document.getElementById("forma").onsubmit = function () {
var ime = document.getElementById("ime").value;
var priimek = document.getElementById("priimek").value;
var stranka = document.getElementById("stranka").value;
try {
var kandidat = Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
document.getElementById("seznam").innerHTML = OblikujIzpis(PridobiPolje());
document.getElementById("obvestila").innerHTML = "Uspešen Vnos!";
document.getElementById("obvestila").className = "bg-success";
}
catch (napaka) {
document.getElementById("obvestila").innerHTML = napaka.message;
document.getElementById("obvestila").className = "bg-danger";
}
document.getElementById("forma").reset();
}
document.getElementById("forma_isci").onsubmit = function () {
var iskani_niz = document.getElementById("iskalniNiz").value;
document.getElementById("seznam").innerHTML = OblikujIzpis(Isci(iskani_niz));
document.getElementById("obvestila").innerHTML = "Rezultat iskanja po iskalnem nizu " + iskani_niz;
document.getElementById("obvestila").className = "bg-info";
}
document.getElementById("pobrisi").onclick = function () {
IzbrisiPolje();
document.getElementById("obvestila").innerHTML = "Polje je bilo izbrisano!";
document.getElementById("obvestila").className = "bg-success";
document.getElementById("seznam").innerHTML = "";
document.getElementById("forma").reset();
}
This is what I tried writing in jquery.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("forma").submit(function(){
var ime=$("ime").val();
var priimek=$("priimek").val();
var stranka=$("stranka").val();
try{
var kandidat= Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
$("seznam").html(OblikujIzpis(PridobiPolje());
$("obvestila").html("Uspešen Vnos!");
$("obvestila").addClass("bg-success");
}
catch(napaka){
$("obvestila").html(napaka.message);
$("obvestila").addClass("bg-danger");
}
$("forma").reset();
$("forma_isci").submit=function(){
var iskani_niz=$("iskaniNiz").val();
$("seznam").html(OblikujIzpis(iskani_niz));
$("obvestila").html("Rezultat iskanja po iskalnem nizu " + iskani_niz);
$("obvestila").addClass("bg-info");
}
$("pobrisi".click=function(){
IzbrisiPolje();
$("obvestila").html("Polje je bilo izbrisano!");
$("obvestila").addClass("bg-success");
$("seznam").html("");
$("forma").reset();
}
}
});
});
</script>
here is my HTML file
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<script src="funkcije.js"></script>
<script src="dom.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>JavaScript - DOM</title>
</head>
<body>
<div class="container">
<h1>Seznam predsedniških kandidatov!</h1>
<form action="#" id="forma_isci" class="form-inline">
<div class="form-group">
<input type="text" class="form-control" id="iskalniNiz" placeholder="Iskalni niz">
</div>
<button type="submit" class="btn btn-info">Išči</button>
</form>
<br />
<br />
<h3>Vnos novih kandidatov</h3>
<form action="#" id="forma" class="form-group">
<table class="table">
<tr>
<td>Ime:</td>
<td>
<input type="text" id="ime" placeholder="Ime kandidata" class="form-control" />
</td>
</tr>
<tr>
<td>Priimek:</td>
<td>
<input type="text" id="priimek" placeholder="Priimek kandidata" class="form-control" />
</td>
</tr>
<tr>
<td>Stranka:</td>
<td>
<select id="stranka" class="form-control" >
<option>Demokratska</option>
<option>Republikanska</option>
<option>Neodvisna</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Dodaj" class="btn btn-info" />
</td>
<td>
<input type="reset" value="Ponastavi" class="btn btn-info" />
</td>
</tr>
</table>
</form>
<br />
<br />
<p id="obvestila"></p>
<br />
<br />
<h3>Seznam obstoječih kandidatov</h3>
<ul id="seznam" class="list"></ul>
<button class="btn" id="pobrisi">Pobriši seznam</button>
</div>
</body>
</html>
So anyway, I'm not going to post the functions here since they're not needed to be seen here.
The javascript code works, the site works then and the elements get added normally. But I would like to have the same effect but written in Jquery. I think some of the issues are in .className, which I replaced with .Addclass from jquery and .innerHTML where I write .html(function). If someone could convert this for me it would be great, since I am kinda new to jquery I'm having some issues.
update n1*
changed the Jquery to this
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
$(document).ready(function(){
$("#forma").submit(function(){
var ime=$("#ime").val();
var priimek=$("#priimek").val();
var stranka=$("#stranka").val();
try{
var kandidat= Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
$("#seznam").html(OblikujIzpis(PridobiPolje());
$("#obvestila").html("Uspešen Vnos!");
$("#obvestila").myClass("bg-success");
}
catch(napaka){
$("#obvestila").html(napaka.message);
$("#obvestila").myClass("bg-danger");
}
$("#forma").reset();
}
$("#forma_isci").submit=function(){
var iskani_niz=$("#iskaniNiz").val();
$("#seznam").html(OblikujIzpis(iskani_niz));
$("#obvestila").html("Rezultat iskanja po iskalnem nizu " + iskani_niz);
$("#obvestila").myClass("bg-info");
}
$("#pobrisi".click=function(){
IzbrisiPolje();
$("#obvestila").html("Polje je bilo izbrisano!");
$("#obvestila").myClass("bg-success");
$("#seznam").html("");
$("#forma").reset();
}
}
});
});
</script>
Added the # where there's an ID, and changed .addClass to .myClass. Add function is still not working. But some other functions are working.
The functions.
var polje = [];
function Kandidat(ime, priimek, stranka) {
if (ime ==="" || priimek === "") {
throw new Error("Podatki niso popolni!");
}
else {
var id = polje.length + 1;
var oseba = {id:id, ime:ime, priimek:priimek, stranka:stranka};
oseba.Izpis = function () {
return "(" + this.id + ")" + this.ime + " " + this.priimek + " pripada stranki " + this.stranka;
}
return oseba;
}
}
function DodajKandidataNaPolje(kandidat) {
polje.push(kandidat);
return true;
}
function PridobiPolje() {
return polje;
}
function OblikujIzpis(polje) {
var izpis = "";
for (var i = 0; i < polje.length; i++) {
izpis = izpis + "<li>" + polje[i].Izpis() + "</li>";
}
return izpis;
}
function Isci(iskalniNiz) {
var rezultat = [];
var oseba;
var vsebuje;
for (var i = 0; i < polje.length; i++) {
oseba = polje[i];
vsebuje = oseba.ime.search(iskalniNiz);
if (vsebuje != -1) {
rezultat.push(oseba);
}
else{
vsebuje = oseba.priimek.search(iskalniNiz);
if (vsebuje != -1) {
rezultat.push(oseba);
}
else{
vsebuje = oseba.stranka.search(iskalniNiz);
if (vsebuje != -1) {
rezultat.push(oseba);
}
}
}
}
return rezultat;
}
function IzbrisiPolje() {
polje = [];
return true;
}
in jQuery, in order to access an element, you need to use a selector. In your case, the form has an id of forma (which in jQuery selectors, you prefix it with #). In order to access your form, you need to do the following:
change this:
$("forma").submit(function(){
to this:
$("#forma").submit(function(){
Anywhere else you use jQuery to access an element in your code would have to be changed as well. use #myid for ids, .myclass for classes. See this for more information.
Here is your code (jQuery section only) with some things fixed:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var forma = $('#forma');
forma.submit(function(){
var ime=$("#ime").val();
var priimek=$("#priimek").val();
var stranka=$("#stranka").val();
try{
var kandidat= Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
$("#seznam").html(OblikujIzpis(PridobiPolje());
$("#obvestila").html("Uspešen Vnos!");
$("#obvestila").addClass("bg-success");
} catch(napaka){
$("#obvestila").html(napaka.message);
$("#obvestila").addClass("bg-danger");
}
forma[0].reset();
});
$("#forma_isci").submit(function(){
var iskani_niz=$("#iskaniNiz").val();
$("#seznam").html(OblikujIzpis(iskani_niz));
$("#obvestila").html("Rezultat iskanja po iskalnem nizu " + iskani_niz);
$("#obvestila").addClass("bg-info");
});
$("#pobrisi").click(function( ){
IzbrisiPolje();
$("#obvestila").html("Polje je bilo izbrisano!");
$("#obvestila").addClass("bg-success");
$("#seznam").html("");
forma[0].reset();
});
});
</script>

This form is submiting but it shouldn't [duplicate]

This question already has answers here:
How to stop form submit during ajax call
(7 answers)
Closed 8 years ago.
I'm working on a website and I have this change_password.php script which is a 3 fields where the user puts his last password, his new password and his new password for a second time. I've tried to make a verification if the second and the third matches. If they don't I show an alert to the user.
The problem is that it does show the alert when the password are different but it redirects to the next page, do_change_password.php anyway. What can I do to fix it?
<html>
<?php
session_start(); // começa a session
require "config.php";
if(Check_Login_Status())
{
Update_Login_Status();
}
else
{
session_unset();
phpAlert_Redirect("ACESSO NEGADO", "index.php");
exit();
}
?>
<head>
<meta charset = 'UTF-8'>
<link rel="shortcut icon" href="images/favicon.ico"/>
<title>Sistema de Estágios - UFMS - Login</title>
<link href = "css/bootstrap.css" rel = "stylesheet" >
<link href = "css/index.css" rel = "stylesheet" >
<script src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("input").blur(function()
{
if($(this).val() == "")
{
$(this).css({"border" : "1px solid #F00"});
}
else
$(this).css({"border" : "1px solid #FFF"});
});
$("#botao").click(function()
{
var cont = 0;
$("#form input").each(function()
{
if($(this).val() == "")
cont++;
});
if(cont == 0)
{
var x = document.forms["Form"]["new_pass"].value;
var y = document.forms["Form"]["conf_pass"].value;
if(x == y)
$("#form").submit();
else
alert("Senhas não conferem");
}
});
});
</script>
</head>
<body>
<?php
Set_Barra_Superior($_SESSION["auto"]);
?>
<center>
<div class = "container">
<div class = "principal">
<form id="form" name="Form" method="post" action="do_change_password.php">
<p>
<label for="a">Senha antiga:</label>
<input id="a" name="old_pass" type="password" class="form-control"/><br/>
</p>
<p>
<label for="b">Nova Senha:</label>
<input id="b" name="new_pass" type="password" class="form-control"/><br/>
</p>
<p>
<label for="c">Confere nova senha:</label>
<input id="c" name="conf_pass" type="password" class="form-control"/><br/>
</p>
<button id="botao" name="botao" value="login" class="btn btn-primary" style="width: 100%;">Login</button>
</form>
</div>
</div>
</center>
</body>
Add the event into the click function, call preventDefault on the event and then return false.
$("#botao").click(function(e)
{
e.preventDefault();
var cont = 0;
$("#form input").each(function()
{
if($(this).val() == "")
cont++;
});
if(cont == 0)
{
var x = document.forms["Form"]["new_pass"].value;
var y = document.forms["Form"]["conf_pass"].value;
if(x == y)
$("#form").submit();
else
alert("Senhas não conferem");
}
return false;
});
Try returning false like:
if(cont == 0)
{
var x = document.forms["Form"]["new_pass"].value;
var y = document.forms["Form"]["conf_pass"].value;
if(x != y)
{
alert("Senhas não conferem");
return false;
}
}

How to read a cookie from javascript and display it in next page(Result.jsp) when body onload

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="JavaScript/CommonJS.js">
</script>
</head>
<body bgcolor="pink">
<div align="center" >
<h1> <font color="red" >JavaScript task</font></h1>
</div>
<div align="left" style="font-family:Verdana; font-size:13px">
Number of Characters Left:
<label id="lblcount" style="background-color:#E2EEF1;
color:Red;font-weight:bold;">100</label><br/>
<textarea style="overflow:auto;resize:none" id="mytextbox"
rows="4" cols="50" maxlength="100" wrap="hard"
onkeyup="LimtCharacters(this,100,'lblcount');"></textarea>
</div>
<p align="center">
<input type="button" id="view" name="view"
value="Next" onclick="SaveData()">
</p>
</body>
This is my index.jsp page when i click on next button it is going to CommonJS.js(javascript) there i'm saving the data in cookie and forwarding to Result.jsp,in Result.jsp page how can i read cookie and display it in my resul.jsp page
Javascript is:
function LimtCharacters(txtMsg, CharLength, indicator) {
var chars = txtMsg.value.length;
document.getElementById(indicator).innerHTML = CharLength - chars;
if (chars > CharLength) {
txtMsg.value = txtMsg.value.substring(0, CharLength);
}
}
function createCookie(cname,cvalue,exdays) {
if (exdays) {
var date = new Date();
date.setTime(date.getTime()+(exdays*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = cname+"="+cvalue+expires+";path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
Anybody guide me thanks in advance.
You can use the body onload="functioncall()" directive to call a function on load. To display it, a simple method would be to have a div in your page that will be filled with the cookie value from JavaScript.
The code would look like this:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function displayCookie() {
document.getElementById('myDiv').innerHTML = readCookie('myCookie');
}
</script>
</head>
<body onload="displayCookie()">
<div id="myDiv" ></div>
</body>

Categories