why Custom Error Dialog Box keeps disappearing? - javascript

I want to make a custom error dialog box, this is the code i used, but whenever i run it, it shows for a second then disappear, I can't find the problem in this code, can anyone help me?
HTML:
<form name="signup" action="" onSubmit="return Validation_for_SignUp" method="post">
<h2 id = "FormTitle"> New Member? Sign up first! </h2>
<label>Username</label>
<input type="text" name="username" id="name"/>
<label>Email</label>
<input type="text" name="email" id="email"/>
<label>Password</label>
<input type="password" name="password" id="password"/>
<label>Confirm Password</label>
<input type="password" name="cpassword" id="cpassword"/>
<button id="Register"onclick="Error.render('Please check the field')"> Sign Up </button>
</form>
JavaScript:
<script>
function CustomError()
{
this.render = function (dialog)
{
var WinWidth = window.innerWidth;
var WinHeight = window.innerHeight;
var ErrorDialog = document.getElementById('ErrorDialog');
var ErrorDialogBox = document.getElementById('ErrorDialogBox');
ErrorDialog.style.display = "block";
ErrorDialog.style.height = WinHeight + "px";
ErrorDialogBox.style.left = (WinWidth/2) - (550 * .05) + "px";
ErrorDialogBox.style.top = "100px";
ErrorDialogBox.style.display = "block";
document.getElementById ('DialogHead').innerHTML = "Warning!";
document.getElementById ('DialogBody').innerHTML = dialog;
ddocument.getElementById ('DialogFoot').innerHTML = '<button onclick = "Error.ok()"> OK </button>';
}
this.ok = function ()
{
document.getElementById('ErrorDialogBox').style.display = "none";
document.getElementById("ErrorDialog").style.display = "none"
}
}
var Error = new CustomError();
</script>
CSS:
#ErrorDialog
{
display: none;
opacity: .8;
position: fixed;
top: 0px;
left: 0px;
background: black;
width: 100%;
z-index: 10;
}
#ErrorDialogBox
{
display: none;
position: fixed;
background: white;
border-radius: 7px;
width: 550px;
z-index: 10;
}
#DialogHead
{
background: #666;
font-size: 19px;
padding: 10px;
color: #CCC;
}
#DialogBody
{
background: #333;
padding: 20px;
color: #FFF;
}
#DialogFoot
{
background: #666;
padding: 20px;
color: #FFF;
}

Hi #wang Hee Ra _ Gogo There is no problem with your code except that the Sign up button posts your form which eventually reload the page, This is the reason why your Dialog dissapear immediatly, And to verify what i'm saying just try to run your Error.render(); function through console or maybe from another button outside the form like:
TEST IT
Clicking this button will show the dialog box and it won't dissapear So maybe you can try to alter your code in a way that does not submit immediatly but after no error is found.
i hope this answer your qustion.

Related

How can I change language on placeholder of a input tag?

I wanted to add a translate toggle button which will translate between two language of a form.
I can select the html tags but how can I select placeholder inside input tag. I've user document.querySelector to select the custom classes I've added only for chagening language. I've also added custom class to input field but couldn't be able to change grab the placeholder text.
here is my html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>language switch using JavaScript</title>
<link rel="stylesheet" href="./main.css">
</head>
<style>
body {
font-family: Roboto, Helvetica, sans-serif;
font-size:20px;
background-color: black;
}
* {
box-sizing: border-box;
}
/* Add padding to containers */
.container {
padding: 16px;
background-color: white;
}
/* Full-width input fields */
input[type=text], input[type=password] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
display: inline-block;
border: none;
background: #f1f1f1;
}
input[type=text]:focus, input[type=password]:focus {
background-color: #ddd;
outline: none;
}
/* Overwrite default styles of hr */
hr {
border: 1px solid #f1f1f1;
margin-bottom: 25px;
}
/* Set a style for the submit button */
.registerbtn {
background-color: #04AA6D;
color: white;
padding: 16px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.9;
font-size: 22px;
}
.registerbtn:hover {
opacity: 1;
}
/* Add a blue text color to links */
a {
color: dodgerblue;
}
/* Set a grey background color and center the text of the "sign in" section */
.signin {
background-color: #f1f1f1;
text-align: center;
}
</style>
<body>
<div class="container">
<div class="langWrap">
EN
<a href="#" language='bangla'>BN</a>
</div>
<div class="content">
<form action="">
<div class="container">
<h1 id="h1title" class="lTitle">Register</h1>
<p class="fillUpInstruction">Please fill in this form to create an account.</p>
<hr>
<label for="email" class="emailLabel"><b>Email</b></label>
<input type="text" placeholder="Enter Email" class="emailPlaceHolder" name="email" id="email" required>
<label for="psw" class="passwordLabel"><b>Password</b></label>
<input type="password" placeholder="Enter Password" class="passwordPlaceHolder" name="psw" id="psw" required>
<label for="psw-repeat" class="repeatPasswordLabel"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" id="psw-repeat" required>
<hr>
<p class="agreementText">By creating an account you agree to our Terms & Privacy
</p>
Terms & Privacy.
<button type="submit" class="registerbtn">Register</button>
</div>
<div class="container signin ">
<p class="questionForExistingAccount">Already have an account?</p>
Sign in.
</div>
</form>
</div>
</div>
</body>
</html>
Here is my script to change language
<script>
const langEl = document.querySelector('.langWrap');
const link = document.querySelectorAll('a');
const lTitle = document.querySelector('.lTitle');
const fillUpInstruction = document.querySelector('.fillUpInstruction');
const emailLabel = document.querySelector('.emailLabel');
const emailPlaceHolder = document.querySelector('.emailPlaceHolder');
const passwordLabel = document.querySelector('.passwordLabel');
const passwordPlaceHolder = document.querySelector('.passwordPlaceHolder');
const repeatPasswordLabel = document.querySelector('.repeatPasswordLabel');
const questionForExistingAccount = document.querySelector('.questionForExistingAccount');
const agreementText = document.querySelector('.agreementText');
const termsPolicy = document.querySelector('.termsPolicy');
const registerbtn = document.querySelector('.registerbtn');
const redirectToExistingAccount = document.querySelector('.redirectToExistingAccount');
link.forEach(el => {
el.addEventListener('click', () => {
langEl.querySelector('.active').classList.remove('active');
el.classList.add('active');
const attr = el.getAttribute('language');
lTitle.textContent = data[attr].lTitle;
fillUpInstruction.textContent = data[attr].fillUpInstruction;
emailLabel.textContent = data[attr].emailLabel;
emailPlaceHolder.textContent = data[attr].emailPlaceHolder;
passwordLabel.textContent = data[attr].passwordLabel;
passwordPlaceHolder.placeholder = data[attr].passwordPlaceHolder;
repeatPasswordLabel.textContent = data[attr].repeatPasswordLabel;
questionForExistingAccount.textContent = data[attr].questionForExistingAccount;
agreementText.textContent = data[attr].agreementText;
termsPolicy.textContent = data[attr].termsPolicy;
registerbtn.textContent = data[attr].registerbtn;
redirectToExistingAccount.textContent = data[attr].redirectToExistingAccount;
});
});
var data = {
"english":
{
"lTitle": "Register",
"fillUpInstruction": "Please fill in this form to create an account.",
"emailLabel": "Email",
// "emailPlaceHolder": "Enter Email",
"passwordLabel": "Enter Password",
"passwordPlaceHolder": "Enter Password",
"repeatPasswordLabel": "Repeat Password",
"questionForExistingAccount": "Already have an account?",
"redirectToExistingAccount": "Sign In",
"agreementText": "By creating an account you agree to our",
"termsPolicy": "Terms & Privacy",
"registerbtn": "Register",
},
"bangla":
{
"lTitle": "নিবন্ধন",
"fillUpInstruction": "দয়া করে অ্যাকাউন্টটি তৈরি করতে এই ফর্মটি পূরণ করুন.",
"emailLabel": "ইমেইল",
"passwordLabel": "পাসওয়ার্ড লিখুন",
"passwordPlaceHolder": "পাসওয়ার্ড লিখুন",
"repeatPasswordLabel": "আবারও পাসওয়ার্ড লিখুন ",
"questionForExistingAccount": "ইতিমধ্যে একটি সদস্যপদ আছে? ",
"redirectToExistingAccount": "সাইন ইন ",
"agreementText": "একটি অ্যাকাউন্ট তৈরি করে আপনি আমাদের শর্তাবলী এবং গোপনীয়তার সাথে সম্মত হবেন ।",
"termsPolicy": "শর্তাবলী এবং গোপনীয়তা",
"registerbtn": "নিবন্ধন",
} ,
}
</script>
I can update your placeholder in this manner using dev tools console:
var attr = "bangla"
emailText = document.querySelector('#email')
emailText.placeholder = data.bangla.emailLabel

javascript multiple field creation issue on limit

i have added button that creates multiple year i want to stop creation of field when number of year is 10. how can i stop this. on year 10?
also i want to disable button once year 10 field is created.
let i = 2;
document.getElementById('add-new-person').onclick = function () {
let template = `
<h3>Year ${i}:</h3>
<p>
<input name="people[${i}][first_name]">
</p>
`;
let container = document.getElementById('people-container');
let div = document.createElement('div');
div.innerHTML = template;
container.appendChild(div);
i++;
}
body {
padding: 2em;
}
[type=submit] {
padding: 0.5em 2em;
}
.add-new-person {
background: #6688dd;
border-radius: 0.25em;
color: #fff;
display: inline-block;
padding: 0.5em;
text-decoration: none;
}
<form method="post">
<div id="people-container">
<h3>Year 1:</h3>
<p>
<input name="people[1][first_name]">
</p>
</div>
Add! new year
<p>
<input type="submit" value="Save">
</p>
</form>
You can use button element instead of a tag. This works better then an a tag. Also, to prevent default behavior of button click we use preventDefault() method. So our page is not reloading each time we click.
To disable your button just set the button attr to disabled to true when the limit reaches years > 10
I have added comments in each line to reflects what happening as well.
Run snippet below to see it working.
//Button
let button = document.getElementById('add-new-person')
//Limit of elements
let i = 2;
//Click function
button.onclick = function(e) {
//Disable default behabviour
e.preventDefault()
//Appending extra years
let template = `
<h3>Year ${i}:</h3>
<p>
<input name="people[${i}][first_name]">
</p>`;
//Checking if the limit is > 10 then we are disabling the button
if (i > 10) {
//Disable button
button.disabled = true;
console.log('Button Disabled')
//Return false
return;
} else {
let container = document.getElementById('people-container');
let div = document.createElement('div');
div.innerHTML = template;
container.appendChild(div);
i++;
}
}
body {
padding: 2em;
}
[type=submit] {
padding: 0.5em 2em;
}
.add-new-person {
background: #6688dd;
border-radius: 0.25em;
color: #fff;
display: inline-block;
padding: 0.5em;
text-decoration: none;
}
<form method="post">
<div id="people-container">
<h3>Year 1:</h3>
<p>
<input name="people[1][first_name]">
</p>
</div>
<button id="add-new-person" class="add-new-person">Add! new year</button>
<p>
<input type="submit" value="Save">
</p>
</form>
I hope it is useful
let i = 2;
document.getElementById('add-new-person').onclick = function () {
//check it if i<=10 do it
if(i <=10){
let template = `
<h3>Year ${i}:</h3>
<p>
<input name="people[${i}][first_name]">
</p>
`;
let container = document.getElementById('people-container');
let div = document.createElement('div');
div.innerHTML = template;
container.appendChild(div);
i++;
}
//if i>10 add deactive class to element
else{
document.getElementById("add-new-person").classList.add("Deactive");
}
}
body {
padding: 2em;
}
[type=submit] {
padding: 0.5em 2em;
}
.add-new-person {
background: #6688dd;
border-radius: 0.25em;
color: #fff;
display: inline-block;
padding: 0.5em;
text-decoration: none;
}
.add-new-person.Deactive{
background: gray;
cursor: not-allowed;
}
<form method="post">
<div id="people-container">
<h3>Year 1:</h3>
<p>
<input name="people[1][first_name]">
</p>
</div>
Add! new year
<p>
<input type="submit" value="Save">
</p>
</form>

JavaScript functions not working together to display image

I am trying to get user input and then print that number of boxes on the screen, I can get the boxes spawning if I do no checks and just set them to spawn whenever I click one, However, once I start adding in checks the boxes just stop spawning.
var count = 1;
function spawnBox() {
var container = document.getElementById("container");
var newBox = document.createElement("div");
newBox.className = "box";
newBox.innerHTML = count;
container.appendChild(newBox);
count++
}
function checkIfCanSpawn() {
while (count < inputNumber) {
spawnBox();
}
}
div.box {
width: 10vw;
height: 8vw;
background: rgb(8, 144, 168);
margin: 1vw;
float: left;
text-align: center;
font-size: 5vw;
padding-top: 1vw;
font-family: sans-serif;
}
<label id="type in a number" name="Input a number"> Type In a number </label>
<input id="inputNum" type="number" name="inputNumber"> </input>
Tweaked a little to make it work.
Added onchange event on input class.
then instead of using the count, i made use of the available while loop and passed the count instead.
then clear the "container" every run.
function spawnBox(count) {
// Get the container
var container = document.getElementById("container");
// Create a new div
var newBox = document.createElement("div");
newBox.className = "box";
newBox.innerHTML = count;
// Append it to the container
container.appendChild(newBox);
// Increment count
count++
}
function checkIfCanSpawn() {
document.getElementById("container").innerHTML = "";
var inputNumber = document.getElementById("inputNum").value;
var x = 1;
while (x <= inputNumber) {
spawnBox(x);
x++;
}
}
div.box {
width: 10vw;
height: 8vw;
background: rgb(8, 144, 168);
margin: 1vw;
float: left;
text-align: center;
font-size: 5vw;
padding-top: 1vw;
font-family: sans-serif;
}
<label id="type in a number" name="Input a number"> Type In a number </label>
<input id="inputNum" type="number" name="inputNumber" onchange="checkIfCanSpawn()" />
<div id="container"></div>
https://jsfiddle.net/Lqj4dktw/
Add a button with a click-eventHandler to call the spawnBox():
$(document).ready(function() {
$("#btn" ).click(function(){
let inputNumber = $("#inputNum").val();
while (count < inputNumber) {
spawnBox();
}
})
})
Her is a working fiddle

How to take back a page to its previous state by clicking the back button of the browser in javascript

I have a page with a link to a form. After clicking the link the form shows up and the link disappears. The problem that i have is, when i click the browser's back button, the values of the URL is changed, but the state of the page doesn't go back to previous state. The form should disappear and the link shows back. Also on reload when the form is visible, the page goes back to its first state, which i need to prevent from happening.
Code :
<html>
<style>
.titimmo {
text-align: center;
padding: 10px;
font-size: 14pt;
background-color: #CC3300;
display: block;
}
.hidden {
display: none;
}
.visible {
display: block;
}
#formContainer {
padding: 1em 0 1em 2em;
background-color: #E8E8E8;
margin: 1em 0 1em 2em;
width: 88.9%;
}
#formContainer h4 {
color: #FF3300;
}
</style>
<body>
<div id="categContainer1">
<div class="titimmo">Real Estate</div>
</div>
<div id="formContainer" class="hidden">
<form action="add.php" method="post">
<h4>Location :</h4>
<input type="text" name="made"/>
<h4>Price :</h4>
<input type="text" name="modele"/><br/><br/>
</form>
</div>
<script>
function stepone() {
document.getElementById('a_categ').onclick = function () {
document.getElementById('categContainer1').className += " hidden";
document.getElementById('formContainer').className = "visible";
window.history.pushState('Form', 'My form', this.getAttribute("href"));
return false
};
}
stepone();
</script>
</body>
</html>
First question is: How to bring back the page to its previous state by clicking the browser's back button?
Second question is: How to prevent the page from going back to its previous state - on reload when it's on second state (when form is visible)?
There are two things you need to do to make it work:
To monitor browser back button click, use
window.onpopstate
method
To remember the form state, you need to store the value in
localStorage or in a cookie.
This is a basic example:
var formVisible = localStorage.formVisible || false;
var cContainer = document.getElementById('categContainer1');
var fContainer = document.getElementById('formContainer');
function formOpen(e) {
cContainer.className = "hidden";
fContainer.className = "visible";
window.history.pushState('Form', 'My form', this.getAttribute("href"));
localStorage.formVisible = 'Y';
return false;
};
function formClose(e) {
cContainer.className = "visible";
fContainer.className = "hidden";
localStorage.removeItem( 'formVisible' );
};
if( formVisible ) formOpen();
document.getElementById('a_categ').onclick = formOpen;
window.onpopstate = formClose;
var formVisible = localStorage.formVisible || false;
var cContainer = document.getElementById('categContainer1');
var fContainer = document.getElementById('formContainer');
function formOpen(e) {
cContainer.className = "hidden";
fContainer.className = "visible";
window.history.pushState('Form', 'My form', this.getAttribute("href"));
localStorage.formVisible = 'Y';
return false;
};
function formClose(e) {
cContainer.className = "visible";
fContainer.className = "hidden";
localStorage.removeItem( 'formVisible' );
};
if( formVisible ) formOpen();
document.getElementById('a_categ').onclick = formOpen;
window.onpopstate = formClose;
.titimmo {
text-align: center;
padding: 10px;
font-size: 14pt;
background-color: #CC3300;
display: block;
}
.hidden {
display: none;
}
.visible {
display: block;
}
#formContainer {
padding: 1em 0 1em 2em;
background-color: #E8E8E8;
margin: 1em 0 1em 2em;
width: 88.9%;
}
#formContainer h4 {
color: #FF3300;
}
<div id="categContainer1">
<div class="titimmo">
Real Estate
</div>
</div>
<div id="formContainer" class="hidden">
<form action="add.php" method="post">
<h4>Location :</h4>
<input type="text" name="made" />
<h4>Price :</h4>
<input type="text" name="modele" />
</form>
</div>
Also on Fiddle, where you can actually see how it works.

Toggle like button to create and remove input box

Am creating an HTML page with some buttons to create the input boxes. The buttons should behave like toggle one. ie, on first click input box should appear and if the same button in clicked again that particular input box need to disappear. Button toggle i have managed. But div is not creating
This is my toggle button
<button class="btn" id="button_rd" onclick="setColor('button_rd', '#101010')";>one</button>
Following is the javascript
var count = 1;
function setColor(btn, color) {
var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "#f4543c"//red
property.style.borderColor = "#f4543c"
count = 1;
}
else {
property.style.backgroundColor = "#00a65a"//green
property.style.borderColor = "#008d4c"
count = 0;
var newdiv = '<div class="form-group"><label for="exampleInputEmail1">email</label>'
+'<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email"></div>'
document.getElementById("create").append(newdiv);
}
}
And below is the place where I need the input box to display(inside this div)
<div class="box-body" id="create">
</div>
If you're happy to use Jquery, Something like this may be what you're looking for.
it's not so much as 'creating' an element, more actually 'toggling' its visibility
$(document).ready(function() {
$('[id^=bool]').click(function() {
var id = $(this).attr("id").substr($(this).attr("id").length - 1);
$('[id^=bool' + id + '] .switcher').toggleClass("switched");
var x = $('[id=input' + id + ']').length;
if (x > 0) //there is one there
{
$('[id=input' + id + ']').remove();
} else {
$('body').append('<input type="text" id="input' + id + '" placeholder="input ' + id + '" />');
}
});
});
.bool {
height: 40px;
width: 100px;
background: darkgray;
position: relative;
border-radius: 5px;
overflow: hidden;
box-shadow: inset 5px 0 6px gray;
border: 1px solid black;
}
.bool:before {
content: "On";
left: 10%;
position: absolute;
top: 25%;
}
.bool:after {
content: "Off";
right: 10%;
position: absolute;
top: 25%;
}
.switcher {
height: 100%;
width: 50%;
position: absolute;
background: lightgray;
top: 0;
left: 0;
z-index: 5;
transform: translateX(0px);
transition: all 0.5s;
border-radius: 5px;
box-shadow: inset 0 0 6px black;
}
.switched {
transform: translateX(50px);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bool" id="bool1">
<div class="switcher"></div>
</div>
<div class="bool" id="bool2">
<div class="switcher"></div>
</div>
Edit History
Altered snippet to include 2 toggles, as per comments
refactored jquery method with help from Tambo
altered markup to 'append' and 'remove' instead
OnClick write following code to hide:
document.getElementById('create').style.display = 'none';
And following code to show:
document.getElementById('create').style.display = 'block';
Like:
JavaScript:
<script type="text/javascript">
var count = 1;
function hidShow()
{
if(count == 1)
{
document.getElementById('create').style.display = 'none';
count = 0;
}
else
{
document.getElementById('create').style.display = 'block';
count = 1;
}
}
</script>
HTML:
<button id="button_rd" onClick="hidShow()">one</button>
<div class="box-body" id="create">
<input type="text" id="txt"/>
</div>
instead of
document.getElementById("create").append(newdiv);
'innerHTML' works for me, like below:
document.getElementById("create").innerHTML = '<div class="form-group"><label for="exampleInputEmail1">email</label>'
+'<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email"></div>'
to remove the div on toggle i used
$('div_id').remove();

Categories