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>
Related
I am trying to toggle between <textarea spellcheck='true'> and <textarea spellcheck='false'>.
Chrome: once spellcheck=true is set, it cannot be "unset", that is, even if you set false, the red underlines do not dissapear (at least on macOS).
Firefox: behaves as expected
Safari: I still don't understand what it is doing, only when I click around I get the red underlines, and then it does not disappear.
I'm suspecting this is OS specific. Reports form other OSs are appreciated.
const textarea = document.querySelector("textarea");
const form = document.querySelector("form");
const output = document.getElementById("output");
textarea.focus();
form.addEventListener("change", (e) => {
const trueOrFalse = e.target.value;
textarea.focus();
textarea.setAttribute("spellcheck", trueOrFalse);
output.textContent = textarea.parentNode.innerHTML;
});
body {
font: 16px/140% monospace;
background: #eee;
color: #777;
padding: 60px;
}
textarea {
margin: 32px 0;
width: 320px;
height: 120px;
font-size: 16px;
}
label {
color: #777;
cursor: pointer;
}
input[type="radio"]:checked + span {
color: #000
}
<form>
<label>
<input type="radio" value="true" name="spellcheck" />
<span>spellcheck true</span>
</label>
<label>
<input type="radio" value="false" name="spellcheck" checked />
<span>spellcheck false</span>
</label>
</form>
<div>
<textarea spellcheck="false">Here is an example of a misspeltz word</textarea>
</div>
<div id="output">
</div>
I found that the implementation (in Chrome, at least) is that the spellcheck mode only works on newly inserted text. In order to completely "reset" the field, you need to remove and reinsert the textarea.
var textarea = document.querySelector("textarea");
const form = document.querySelector("form");
const output = document.getElementById("output");
textarea.focus();
form.addEventListener("change", (e) => {
const trueOrFalse = e.target.value;
const text = textarea.value;
textarea.parentNode.removeChild(textarea);
textarea = document.createElement("textarea");
textarea.textContent = text;
document.querySelector(".textarea-container").appendChild(textarea);
textarea.focus();
textarea.setAttribute("spellcheck", trueOrFalse);
output.textContent = textarea.parentNode.innerHTML;
});
body {
font: 16px/140% monospace;
background: #eee;
color: #777;
padding: 60px;
}
textarea {
margin: 32px 0;
width: 320px;
height: 120px;
font-size: 16px;
}
label {
color: #777;
cursor: pointer;
}
input[type="radio"]:checked + span {
color: #000
}
<form>
<label>
<input type="radio" value="true" name="spellcheck" />
<span>spellcheck true</span>
</label>
<label>
<input type="radio" value="false" name="spellcheck" checked />
<span>spellcheck false</span>
</label>
</form>
<div class="textarea-container">
<textarea spellcheck="false">Here is an example of a misspeltz word</textarea>
</div>
<div id="output">
</div>
When the user gets to the end of this quiz a reset button is present. I have tried everything I can find to make the reset button work. I've added it to the top, I've wrapped in a form tag as well and tried "reset form". I'm a novice, so I would appreciate knowing what I may be doing wrong and if this is even a possibility with my current formatting.
Full code below.
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
// Displays the specified tab of the form
function showTab(n) {
var x = document.getElementsByClassName('tab');
x[n].style.display = 'block';
// Fix the Previous button
if (n == 0) {
document.getElementById('prevBtn').style.display = 'none';
} else {
document.getElementById('prevBtn').style.display = 'inline';
}
// Fix the Next button
if (n == (x.length - 1)) {
document.getElementById('nextBtn').innerHTML = 'restart';
} else {
document.getElementById('nextBtn').innerHTML = 'Next';
}
// Run a function that will display the correct step indicator
fixStepIndicator(n)
}
// Figures out which tab to display
function nextPrev(n) {
var x = document.getElementsByClassName('tab');
// Exit the function if any field in the current tab is invalid
if (n == 1 && !validateForm()) return false;
// Hide the current tab
x[currentTab].style.display = 'none';
// Increase or decrease the current tab by 1
currentTab = currentTab + n;
// if you have reached the end of the form...
if (currentTab >= x.length) {
// ... the form gets restarted:
document.getElementById('regForm').restart();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
// Validates the form fields
function validateForm() {
var x, y, i, valid = true;
x = document.getElementsByClassName('tab');
y = x[currentTab].getElementsByTagName('input');
// Checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == '') {
// add an "invalid" class to the field
y[i].className += ' invalid';
// and set the current valid status to false
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName('step')[currentTab].className += ' finish';
}
return valid; // return the valid status
}
// Removes the "active" class of all steps
function fixStepIndicator(n) {
var i, x = document.getElementsByClassName('step');
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(' active', '');
}
//... and add the "active" class on the current step
x[n].className += ' active';
}
function yesnoCheck() {
if (document.getElementById('yesCheck').checked) {
document.getElementById('ifYes').style.display = 'block';
} else {
document.getElementById('ifYes').style.display = 'none';
}
if (document.getElementById('noCheck').checked) {
document.getElementById('ifNo').style.display = 'block';
} else {
document.getElementById('ifNo').style.display = 'none';
}
}
function yesno1Check() {
if (document.getElementById('yes1Check').checked) {
document.getElementById('ifYes1').style.display = 'block';
} else {
document.getElementById('ifYes1').style.display = 'none';
}
if (document.getElementById('no1Check').checked) {
document.getElementById('ifNo1').style.display = 'block';
} else {
document.getElementById('ifNo1').style.display = 'none';
}
}
* {
box-sizing: border-box;
}
body {
background-color: #f1f1f1;
padding-bottom: 5rem;
}
#regForm {
background-color: #ffffff;
margin: 50px auto;
font-family: calibri;
font-size: 17px
padding: 40px;
width: 30%;
min-width: 300px;
}
h1 {
text-align: center;
}
input {
padding: 10px;
width: 100%;
font-size: 17px;
font-family: Raleway;
border: 1px solid #aaaaaa;
}
/* Mark input boxes that gets an error on validation: */
input.invalid {
background-color: #ffdddd;
}
/* Hide all steps by default: */
.tab {
display: none;
}
button {
background-color: #0000ff;
color: #ffffff;
border: none;
padding: 10px 20px;
font-size: 17px;
font-family: Raleway;
cursor: pointer;
}
button:hover {
opacity: 0.8;
}
#prevBtn {
background-color: #bbbbbb;
}
/* Make circles that indicate the steps of the form: */
.step {
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbbbbb;
border: none;
border-radius: 50%;
display: inline-block;
opacity: 0.5;
}
.step.active {
opacity: 1;
}
/* Mark the steps that are finished and valid: */
.step.finish {
background-color: #0000ff;
}
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet" />
<span style="font-family: calibri; font-size: 12pt;">
<form id="regForm" style="float: left;">
<h1 style="text-align: left;">Voicemail Troubleshooting</h1>
<!-- One "tab" for each step in the form: -->
<div class="tab">
Is the accurate SKU on the LOS?<br /><br />
Yes <input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="yesCheck">
No <input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="noCheck"><br />
</div>
<div class="tab">
Tab 2
<div id="ifNo" style="display: none">
Result of selecting No to first question
</div>
<div id="ifYes" style="display: none"><br /><br />
Can the customer call the VM from their phone?<br /><br />
Yes <input type="radio" onclick="javascript:yesno1Check();" name="yesno1" id="yes1Check">
No <input type="radio" onclick="javascript:yesno1Check();" name="yesno1" id="no1Check"><br />
</div>
</div>
<div class="tab">
Tab 3
<div id="ifYes1" style="display:none"><br />
Result of selecting Yes to second question.
</div>
<div id="ifNo1" style="display:none">
Result of selecting No to second question</div>
</div>
<div style="overflow: auto;">
<div style="float: right;">
<br /><br />
<button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
</div>
</div>
<!-- Circles which indicates the steps of the form: -->
<div style="text-align: center; margin-top: 40px;">
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
</div>
</form>
</span>
I think it what you want -
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet" />
<style>
* {
box-sizing: border-box;
}
body {
background-color: #f1f1f1;
}
#regForm {
background-color: #ffffff;
margin: 50px auto;
font-family: calibri;
font-size: 17px
padding: 40px;
width: 30%;
min-width: 300px;
}
h1 {
text-align: center;
}
input {
padding: 10px;
width: 100%;
font-size: 17px;
font-family: Raleway;
border: 1px solid #aaaaaa;
}
/* Mark input boxes that gets an error on validation: */
input.invalid {
background-color: #ffdddd;
}
/* Hide all steps by default: */
.tab {
display: none;
}
button {
background-color: #0000ff;
color: #ffffff;
border: none;
padding: 10px 20px;
font-size: 17px;
font-family: Raleway;
cursor: pointer;
}
button:hover {
opacity: 0.8;
}
#prevBtn {
background-color: #bbbbbb;
}
/* Make circles that indicate the steps of the form: */
.step {
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbbbbb;
border: none;
border-radius: 50%;
display: inline-block;
opacity: 0.5;
}
.step.active {
opacity: 1;
}
/* Mark the steps that are finished and valid: */
.step.finish {
background-color: #0000ff;
}
</style>
<span style="font-family: calibri; font-size: 12pt;">
<form id="regForm" style="float: left;">
<h1 style="text-align: left;">Voicemail Troubleshooting</h1>
<!-- One "tab" for each step in the form: -->
<div class="tab">
Is the accurate SKU on the LOS?<br />
<br />
Yes <input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="yesCheck">
No <input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="noCheck"><br />
</div>
<div class="tab">Tab 2
<div id="ifNo" style="display:none">
Result of selecting No to first question
</div>
<div id="ifYes" style="display:none"><br />
<br />
Can the customer call the VM from their phone?<br />
<br />
Yes <input type="radio" onclick="javascript:yesno1Check();" name="yesno1" id="yes1Check">
No <input type="radio" onclick="javascript:yesno1Check();" name="yesno1" id="no1Check"><br />
</div>
</div>
<div class="tab">Tab 3
<div id="ifYes1" style="display:none"><br />
Result of selecting Yes to second question.</div>
<div id="ifNo1" style="display:none">
Result of selecting No to second question</div>
</div>
<div style="overflow: auto;">
<div style="float: right;">
<br />
<br />
<button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
</div>
</div>
<!-- Circles which indicates the steps of the form: -->
<div style="text-align: center; margin-top: 40px;">
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
</div>
</form>
</span>
<script>
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
function showTab(n) {
// This function will display the specified tab of the form...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
//... and fix the Previous/Next buttons:
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").innerHTML = "restart";
document.getElementById("nextBtn").setAttribute('onclick', 'restart()');
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
//... and run a function that will display the correct step indicator:
fixStepIndicator(n);
}
/* Restart function */
function restart(){
var x = document.getElementsByClassName("tab");
x[x.length - 1].style.display = "none";
document.getElementById("nextBtn").setAttribute('onclick', 'nextPrev(1)');
window.currentTab = 0; // Current tab is set to be the first tab (0)
showTab(window.currentTab); // Display the current tab
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
if (n == 1 && !validateForm()) return false;
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form...
if (currentTab >= x.length) {
// ... the form gets restarted:
document.getElementById("regForm").restart();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
function fixStepIndicator(n) {
// This function removes the "active" class of all steps...
var i, x = document.getElementsByClassName("step");
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(" active", "");
}
//... and adds the "active" class on the current step:
x[n].className += " active";
}
</script><script>
function yesnoCheck() {
if (document.getElementById('yesCheck').checked) {
document.getElementById('ifYes').style.display= 'block';
}
else document.getElementById('ifYes').style.display= 'none';
if (document.getElementById('noCheck').checked) {
document.getElementById('ifNo').style.display= 'block';
}
else document.getElementById('ifNo').style.display= 'none';
}</script><script>
function yesno1Check() {
if (document.getElementById('yes1Check').checked) {
document.getElementById('ifYes1').style.display= 'block';
}
else document.getElementById('ifYes1').style.display= 'none';
if (document.getElementById('no1Check').checked) {
document.getElementById('ifNo1').style.display= 'block';
}
else document.getElementById('ifNo1').style.display= 'none';
}
});</script>
Working fiddle - jsfiddle link
Here is the method I’m trying to make. Basically what it’s supposed to do is, when an <input> with the type of button is clicked, it makes the next <div> (in this case hard-coded) go from display: none to display: block. However it’s not working.
matchDivs() {
let showInputs = document.querySelectorAll('input')
const inputs = Array.from(showInputs)
inputs.map(input => {
if (input.parentNode.getAttribute('class') === 'first-employee') {
document.querySelector('.second-employee').setAttribute('style', 'display: block')
}
return input
})
}
When you use if (node.getAttribute('class') === 'first-employee') this is return:
class='first-employee' // true
class='employee first-employee' // false
You must use:
if (node.classList.contains("first-employee")):
class='first-employee' // true
class='employee first-employee' // true
If I have understand your question properly that on button click you want to show/hide DIV tag next to it, which is inside common parent div for both, button and 'second-employee'.
I think below will be helpful.
// For single Div show/hide on button click
let btnMatchDiv = document.querySelector('#btnMatchDivs');
btnMatchDiv.addEventListener('click', matchDivs, true);
function matchDivs() {
let showInputs = document.querySelectorAll('input')
const inputs = Array.from(showInputs)
inputs.map(input => {
// Method 1
// ===========================
/*if (input.parentNode.getAttribute('class') === 'first-employee') {
document.querySelector('.second-employee').setAttribute('style', 'display: block')
}*/
// Method 2 : you can use new classList method
// ===========================
if (input.parentNode.classList.contains('first-employee')) {
input.nextElementSibling.classList.toggle('hidden');
}
//return input
})
}
body {
font-family: Arial;
}
.first-employee {
display: block;
padding: 1em;
border: 1px solid green;
}
.second-employee {
padding: 1em;
border: 1px solid red;
}
#btnMatchDivs {
padding: 1em 0.5em;
border: 1px solid #777;
}
.hidden {
display: none
}
<div class="first-employee">
<h2>
First Employee
</h2>
<input type="button" id="btnMatchDivs" value="Toggle Second Employee" />
<div class="second-employee hidden">
Second Employee
</div>
</div>
Please let me know if you need further help on this.
Thanks,
Jignesh Raval
Also if you want to toggle multiple items then you can try below code.
// For multiple Div show/hide on button click
// ===================================
let showInputs = document.querySelectorAll('input')
const btnInputs = Array.from(showInputs)
// Bind click event to each button input
btnInputs.map(input => {
input.addEventListener('click', matchDivs, false);
})
function matchDivs(event) {
let buttonEle = event.currentTarget;
if (buttonEle.parentNode.classList.contains('first-employee')) {
buttonEle.nextElementSibling.classList.toggle('hidden');
}
}
body {
font-family: Arial;
}
.first-employee {
display: block;
padding: 1em;
border: 1px solid green;
margin-bottom: 1em;
}
.second-employee {
margin: 1em 0;
padding: 1em;
border: 1px solid red;
}
#btnMatchDivs {
padding: 1em 0.5em;
border: 1px solid #777;
}
.hidden {
display: none
}
<div class="first-employee">
<h2>
First Employee 1
</h2>
<input type="button" id="btnMatchDivs" value="Match Divs" />
<div class="second-employee hidden">
Second Employee 1
</div>
</div>
<div class="first-employee">
<h2>
First Employee 2
</h2>
<input type="button" id="btnMatchDivs" value="Match Divs" />
<div class="second-employee hidden">
Second Employee 2
</div>
</div>
<div class="first-employee">
<h2>
First Employee 3
</h2>
<input type="button" id="btnMatchDivs" value="Match Divs" />
<div class="second-employee hidden">
Second Employee 3
</div>
</div>
I hope this will be helpful.
Thanks,
Jignesh Raval
I'm creating a to-do list app, and in the app there is a div that wraps an input box (for the to-do item and so the user can edit the to-do) and a icon from font-awesome. When the user clicks on the icon, I want the entire div (which contains the to-do and the delete icon) to be deleted. But when tried to do that, it didn't work. Can someone help me?
Here's the JS Code
$(document).ready(() => {
$(".input input").on("keypress", check_todo);
$(".fa-trash").on("click", ".todo_container", delete_todo);
})
// delete todo
let delete_todo = (e) => {
e.target.remove();
}
// add todo
let add_todo = () => {
let todo = $(".input input").val();
$(".output").append(`
<input type="text" placeholder="Edit To-do" value="${todo}"><i class="fa fa-trash fa-lg" aria-hidden="true"></i>
`);
$(".input input").val("");
}
// check todo
let check_todo = (e) => {
if (e.keyCode == 13) {
if ($(".input input").val() == "") {
no_todo();
} else {
add_todo();
}
}
}
// no todo
let no_todo = () => {
alert("Please add a new todo");
}
See the html and a demo
You should binding to .out-put container.
$(".output").on("click",".fa-trash" , delete_todo);
http://codepen.io/Vrety/pen/WoWmaE
http://codepen.io/anon/pen/eBoXZe
In your event listener, you need to swap ".todo_container" and ".fa-trash".
$(".todo_container").on("click",".fa-trash" , delete_todo);
This statement means, when a click event occurs and bubbles up to .todo_container, check if the clicked element is .fa-trash, if so call the function.
Then change your delete function
let delete_todo = (e) => {
$(e.currentTarget).closest('.todo_container').remove()
}
This code means from the clicked icon, travel up the dom to find .todo_container, then remove it.
Good job with using the delegation in JQuery but while using it
$(".todo_container").on("click",".fa-trash" , delete_todo);
The base element $(".todo_container") needs to be static, You are deleting this also in the delete_todo() function.
Try using $(".output") instead and see if it works.
here is a working code
$(document).ready(function() {
$(".input input").on("keypress", check_todo);
//$(".fa-trash").on("click", ".todo_container", delete_todo);
$(".todo_container .fa-trash").on("click", delete_todo);
})
// delete todo
let delete_todo = function(e) {
//e.target.remove();
$(e.target).parent().remove();
}
// add todo
let add_todo = function() {
let todo = $(".input input").val();
//to do container element, the delete icon will added later
var toDoContainer = $(`
<div class="todo_container">
<input type="text" placeholder="Edit To-do" value="${todo}"></div>
`);
//create delete icon and set event listener
var elem = $('<i class="fa fa-trash fa-lg" aria-hidden="true"></i>').on("click", delete_todo).appendTo(toDoContainer);
$(".output").append(toDoContainer);
$(".input input").val("");
}
// check todo
let check_todo = (e) => {
if (e.keyCode == 13) {
if ($(".input input").val() == "") {
no_todo();
} else {
add_todo();
}
}
}
// no todo
let no_todo = () => {
alert("Please add a new todo");
}
#font-face {
font-family: Open Sans;
src: url("assets/fonts/OpenSans-Regular");
font-weight: 400
}
#font-face {
font-family: Open Sans;
src: url("assets/fonts/OpenSans-Semibold");
font-weight: 600
}
* {
margin: 0;
padding: 0;
transition: all 200ms ease-in-out;
}
*::selection {
background-color: #ffffaa;
}
.container {
width: 60%;
margin: 20px auto;
}
.header {
padding: 10px;
}
.header input {
padding: 10px;
width: 60%;
border: none;
outline: none;
font: 400 1.8em Open Sans;
}
.to-do {
padding: 10px;
text-align: center;
}
.input input {
padding: 10px;
width: 40%;
border: none;
outline: none;
font: 600 1em Open Sans;
border-bottom: 3px solid #333;
}
.output {
margin: 10px;
}
.output input {
padding: 20px;
border: none;
outline: none;
font: 600 1em Open Sans;
width: 50%;
cursor: pointer;
}
.output input:hover {
background-color: #eee;
}
.fa-trash {
padding: 20px;
cursor: pointer;
}
.fa-trash:hover {
background-color: #333;
color: #fff;
}
<head>
<title>To-do List</title>
<!-- FONTS -->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,500" rel="stylesheet">
</head>
<body>
<div class="container">
<header class="header">
<input type="text" name="edit_name" placeholder="Edit Name">
</header>
<section class="to-do">
<div class="input">
<input type="text" name="add_todo" placeholder="Click To Add A New To-do">
</div>
<div class="output">
<div class="todo_container">
<input type="text" placeholder="Edit To-do" value="Todo #1"><i class="fa fa-trash fa-lg" aria-hidden="true"></i>
</div>
<div class="todo_container">
<input type="text" placeholder="Edit To-do" value="Todo #2"><i class="fa fa-trash fa-lg" aria-hidden="true"></i>
</div>
</div>
</section>
</div>
<!-- JQUERY -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://use.fontawesome.com/5840114410.js"></script>
</body>
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.