Requirements:
When more than one button is clicked, users will then be able to click on "proceed-button".
Current situation:
I am making a cinema web page. Users will get to choose their preferred seats. When the seat is chosen, they will then be able to click on "proceed-button" to pay. However, i have difficulty implementing this function. I know that i needed to use the visibility-hidden function.
The following is my code:
var buttons = document.getElementsByClassName("button");
var count = 0;
var disp = document.getElementById("display");
for (let i = 0, l = buttons.length; i < l; i++) {
buttons[i].addEventListener('click', function() {
buttons[i].classList.toggle('active');
if (this.classList.contains("active")) {
count++;
if (this.classList.contains("active") > 1) {
function proceedButton() {
document.getElementById("pButton").style.display = "visible";
}
} else {
document.getElementById("pButton").style.display = "block";
}
} else {
count--;
}
disp.innerHTML = count;
})
}
function proceedButton() {
var x = document.getElementById("payment-section");
if (x.style.display === "none") {
x.style.display = "block";
}
}
.button {
background-color: #423F3E;
height: 30px;
width: 30px;
margin: 5px;
border-radius: 10px;
border: none;
float: left;
}
.button.active {
background-color: #F7EA00 !important;
}
<div class="seats-layout">
<div class="row">
<input type="button" id="button1" class="button" />
<input type="button" id="button2" class="button" />
<input type="button" id="button3" class="button" />
</div>
<div class="row">
<input type="button" id="button1" class="button" />
<input type="button" id="button2" class="button" />
<input type="button" id="button3" class="button" />
</div>
</div>
<p> Button Clicked <span id="display">0</span> Times</p>
<input type="submit" value="Proceed" onclick="proceedButton()" id="pButton" class="proceed-button" />
```
<div id="payment-section" style="display: none">
<h1>Payment</h1>
</div>
```
Demo page
use document.querySelectorAll to returns all elements in the document that matches a specified CSS selector(s), as a static NodeList object.
function proceedButton() {
var x = document.getElementById("payment-section");
var item_click = document.querySelectorAll('.active').length;
if (item_click>1) {
x.style.display = "block";
}else{
x.style.display = "none";
}
}
Related
When I click on the button "Change/Add text to this picture" and input values in the two fields with id="top-distance" and id="left-distance" then click on the button "Done", those values should be set as the top and left css properties of the #img-text element. I tried to do that in the doneFunction() below but it doesn't work:
var pics = [['https://www.planwallpaper.com/static/images/ziiQN6XE5_UCWiCRXMT0B3p.jpg', 'Изображение 1'], ['https://www.planwallpaper.com/static/images/nature-wallpapers-free-download-1.jpg', 'Изображение 2'], ['https://www.planwallpaper.com/static/images/Beautiful_Wallpaper_1080p_Full_HD.jpg', 'Изображение 3'], ['https://www.planwallpaper.com/static/images/1080p-wallpaper-14854-15513-hd-wallpapers.jpg', 'Изображение 4'], ['https://static.pexels.com/photos/20974/pexels-photo.jpg', 'Изображение 5']];
var counter = 0;
function showImage() {
document.getElementById('main-pic').src = pics[counter][0];
document.getElementById('img-text').innerHTML = pics[counter][1];
//или чрез задаване на таг img тук: document.getElementById(...).innerHTML = '<img alt="Природа" class="main-pic" title="Природа" src="' + pics[counter][0] + '" />';
}
showImage();
function previousImg() {
if (counter == 0) {
alert('Няма предишно изображение.');
} else {
counter--;
}
showImage();
}
function nextImg() {
if (counter == pics.length - 1) {
alert('Няма следващо изображение.');
} else {
counter++;
}
showImage();
}
function addImg() {
var someURL = prompt('Посочете url на изображението, което желаете да добавите.', 'https://www.picwallz.com/wp-content/uploads/2017/02/desktop-natural-beauty-cave-with-nature-pics-high-quality-for-mobile-phones-v-898x505.jpg');
if (someURL == null) {
alert('Вие отказахте добавянето на ново изображение.');
return;
}
function isValidURL(stringURL) {
var pattern = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
if (!pattern.test(stringURL)) {
alert("Не сте въвели url адрес, опитайте пак!");
return false;
} else {
return true;
}
}
if (isValidURL(someURL)) {
pics.push([someURL, 'Text']);
}
}
function changeAddText() {
document.getElementById('hidden-div').style.display = 'block';
}
function doneFunction() {
document.getElementById('hidden-div').style.display = 'none';
pics[counter][1] = document.getElementById('new-text').value;
//document.getElementById('img-text').style.top.value = document.getElementById('top-distance').value;
var pText = document.getElementById('img-text');
var topText = document.getElementById('top-distance').value;
if (!isNaN(topText) && (topText <= 200)) {
pText.style.top = topText;
} else {
alert('Please insert a number <=200.');
}
var leftText = document.getElementById('left-distance').value;
if (!isNaN(leftText) && (topText <= 100)) {
pText.style.left = leftText;
} else {
alert('Please insert a number <=100.');
}
showImage();
}
#main-pic {
position: relative;
width: 500px;
height: 350px;
}
#img-text {
color: white;
position: absolute;
top: 5px;
left: 20px;
}
.button {
height: 40px;
background-color: lightblue;
}
#hidden-div {
display: none;
}
<img id="main-pic" alt="Природа" title="Природа" /><br />
<p id="img-text"></p>
<br />
<input class="button" type="button" name="previous" value="Prev" onclick="previousImg(); return false;" />
<input class="button" type="button" name="next" value="Next" onclick="nextImg(); return false;" />
<input class="button" type="button" name="next" value="Add picture" onclick="addImg(); return false;" />
<input class="button" type="button" name="change-add-text" value="Change/Add text to this picture" onclick="changeAddText(); return false;" />
<div id="hidden-div">
<input id="new-text" type="text" name="new-text" placeholder="Your text" value="Picture" />
<input type="number" id="top-distance" name="topText" min="0" max="200" step="5" placeholder="top" />
<input type="number" id="left-distance" name="leftText" min="0" max="100" step="5" placeholder="left" />
<input class="button" type="button" name="done-button" value="Done" onclick="doneFunction(); return false;" />
</div>
You need to include the units when setting the position.
Change these lines:
pText.style.top = topText;
pText.style.left = leftText;
to:
pText.style.top = topText + 'px';
pText.style.left = leftText + 'px';
I have a main div and the sub div which is also called form because form is wrapped inside of div. I want is to close the form when clicked outside of the main div but it's not happening at all. Please help me how to fix this.
var btn = document.getElementById('opener');
var box = document.getElementById('abc');
var form = document.getElementById('def');
btn.onclick = function(){
box.style.display = "block";
}
//Doesn't work. It's function is to close the form when click outside of the div.
window.onclick = function(event){
if(event.target == box){
form.style.display = "none";
}
}
#abc{
display: none;
background-color: #F44336;
}
<button id = "opener">
Open
</button>
<div id = "abc">
<!-- Login Authentication -->
<div id = "def">
<div>
<p>Welcome</p>
</div>
<br />
<div class = "login-auth" id = "cool">
<form method="POST">
<label>Email or Username:</label>
<input type = "text">
<br />
<label>Password:</label>
<input type = "password">
<br /><br />
<input type="submit" value="Login">
</form>
</div>
</div>
</div>
JSFiddle Link Here: https://jsfiddle.net/twrvpp3d/
Your code is working fine, the only problem that you need to stop the click event from propagating by using e.stopPropagation() for the button and the popup window, this will create the desired effect! Refer my below snippet!
#def{
border:1px solid black;
}
#abc{
padding:40px;
}
var btn = document.getElementById('opener');
var box = document.getElementById('abc');
var form = document.getElementById('def');
btn.onclick = function(e) {
e.stopPropagation();
box.style.display = "block";
}
box.onclick = function(e) {
e.stopPropagation();
}
//Doesn't work. It's function is to close the form when click outside of the div.
window.onclick = function(event) {
box.style.display = "none";
}
#abc {
display: none;
background-color: #F44336;
}
#def {
border: 1px solid black;
}
#abc {
padding: 40px;
}
<button id="opener">
Open
</button>
<div id="abc">
<!-- Login Authentication -->
<div id="def">
<div>
<p>Welcome</p>
</div>
<br />
<div class="login-auth" id="cool">
<form method="POST">
<label>Email or Username:</label>
<input type="text">
<br />
<label>Password:</label>
<input type="password">
<br />
<br />
<input type="submit" value="Login">
</form>
</div>
</div>
</div>
I know this is not what you are asking but can you make toggle button? its easier to do and more obvious for user.
var btn = document.getElementById('opener');
var box = document.getElementById('abc');
var form = document.getElementById('def');
btn.onclick = function(e){
if(e.target.innerHTML === 'Open'){
box.style.display = "block";
e.target.innerHTML = "Close"
}else{
box.style.display = "none";
e.target.innerHTML = "Open"
}
}
//Doesn't work. It's function is to close the form when click outside of the div.
window.onclick = function(event){
if(event.target == box){
form.style.display = "none";
}
}
#abc{
display: none;
background-color: #F44336;
}
<button id = "opener">
Open
</button>
<div id = "abc">
<!-- Login Authentication -->
<div id = "def">
<div>
<p>Welcome</p>
</div>
<br />
<div class = "login-auth" id = "cool">
<form method="POST">
<label>Email or Username:</label>
<input type = "text">
<br />
<label>Password:</label>
<input type = "password">
<br /><br />
<input type="submit" value="Login">
</form>
</div>
</div>
</div>
window.onclick does not work on certain browsers. Try document.onclick instead.
This how the code works, when i press left key button (e.keyCode =39) it jumps up to the next page. All in all there are 7 ($('#btn-group input').length) pages in my program. I tried using preventDefault(); command inside the condition where the comment i dont know hat will put here but i wont work on my program( it jumps to page 8 and returns to page 7). Thank you
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '39') {
var old_num = $('#btn-group').find('.active-btn').val();
var new_num = +old_num + 1;
$('#page' + old_num).toggle('slide', {
direction: 'left',
complete: function() {
$('#btn_page' + old_num).removeClass('active-btn');
$('#page' + old_num).clearQueue();
$('#page' + old_num).removeClass('active-page');
$('#page' + new_num).addClass('active-page');
$('#btn_page' + new_num).addClass('active-btn');
if (new_num == $('#btn-group input').length) {
// i dont know what will put here
}
$('#page' + new_num).toggle('slide', {
direction: 'right'
});
}
});
}
}
<div class="pull-right" id="btn_all">
<input class="btn active-btn" type="button" id="prev_btn" style="background-color:#66cdaa" style="width:70px;margin:1em" value="Prev.">
<div class="btn-group" id="btn-group">
<br>
<input class="btn butt active-btn" type="button" id="btn_page1" style ="background-color:#66cdaa" value="1">
<input class="btn butt" type="button" id="btn_page2" style ="background-color:#66cdaa" value="2">
<input class="btn butt" type="button" id="btn_page3" style ="background-color:#66cdaa" value="3">
<input class="btn butt" type="button" id="btn_page4" style ="background-color:#66cdaa" value="4">
<input class="btn butt" type="button" id="btn_page5" style ="background-color:#66cdaa" value="5">
<input class="btn butt" type="button" id="btn_page6" style ="background-color:#66cdaa" value="6">
<input class="btn butt" type="button" id="btn_page7" style ="background-color:#66cdaa" value="7">
<input class="btn butt active-btn" type="button" style ="background-color:#66cdaa" id="next_btn" value="Next">
</div>
You can call this function on keypress of an element.
function ValidateClientname(e, t) {
try {
if (window.event) {
var charCode = window.event.keyCode;
} else if (e) {
var charCode = e.which;
} else {
return true;
}
alert (charCode); // this will give you key value and you can pass it in if statement like if ((charCode > 47 && charCode < 58) || (charCode ==8))
if ((charCode > 47 && charCode < 58) )
return true;
else
return false;
} catch (err) {
alert(err.Description);
}
}
You need to "short circuit" your function before it reaches the .toggle function. This will prevent all further execution of the function.
$(function() {
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '39') {
var old_num = $('#btn-group').find('.active-btn').val();
var new_num = +old_num + 1;
// if new number is for a page that doesnt exist
// short circuit
if (new_num == $('#btn-group input').length) {
return false;
}
$('#page' + old_num).toggle('slide', {
direction: 'left',
complete: function() {
$('#btn_page' + old_num).removeClass('active-btn');
$('#page' + old_num).removeClass('active-page');
$('#page' + new_num).addClass('active-page');
$('#btn_page' + new_num).addClass('active-btn');
$('#page' + new_num).toggle('slide', {
direction: 'right'
});
}
});
}
}
});
.active-btn {
background-color: red !important;
}
.page {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<div class="pull-right" id="btn_all">
<input class="btn active-btn" type="button" id="prev_btn" style="background-color:#66cdaa" style="width:70px;margin:1em" value="Prev.">
<div class="btn-group" id="btn-group">
<input class="btn butt active-btn" type="button" id="btn_page1" style="background-color:#66cdaa" value="1" />
<input class="btn butt" type="button" id="btn_page2" style="background-color:#66cdaa" value="2" />
<input class="btn butt" type="button" id="btn_page3" style="background-color:#66cdaa" value="3" />
<input class="btn butt" type="button" id="btn_page4" style="background-color:#66cdaa" value="4" />
<input class="btn butt" type="button" id="btn_page5" style="background-color:#66cdaa" value="5" />
<input class="btn butt" type="button" id="btn_page6" style="background-color:#66cdaa" value="6" />
<input class="btn butt" type="button" id="btn_page7" style="background-color:#66cdaa" value="7" />
<input class="btn butt active-btn" type="button" style="background-color:#66cdaa" id="next_btn" value="Next" />
</div>
</div>
<div id="pages_all">
<div id="page1" class="page active-page" style="display:block">Page 1</div>
<div id="page2" class="page">Page 2</div>
<div id="page3" class="page">Page 3</div>
<div id="page4" class="page">Page 4</div>
<div id="page5" class="page">Page 5</div>
<div id="page6" class="page">Page 6</div>
<div id="page7" class="page">Page 7</div>
</div>
you can try this:
$('.btn').click(function(){
$(this).addClass('active-btn').siblings().removeClass('active-btn');
});
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
var old_num = parseInt($('#btn-group').find('.active-btn').val());
var new_num = old_num+1;
if (new_num == $('#btn-group input').length) {
new_num=1;
}
if (e.keyCode == '39') {
$('#page' + old_num).toggle('slide', {
direction: 'left',
complete: function() {
$('#btn_page' + old_num).removeClass('active-btn');
$('#page' + old_num).clearQueue();
$('#page' + old_num).removeClass('active-page');
$('#page' + new_num).addClass('active-page');
$('#btn_page' + new_num).addClass('active-btn');
$('#page' + new_num).toggle('slide', {
direction: 'right'
});
}
});
}
}
.pager:not(:first-child) { display:none;}
.butt{background-color:#66cdaa}
.active-btn {background-color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<p id="page1" class="pager" style="display:inline-block">1</p>
<p id="page2" class="pager">2</p>
<p id="page3" class="pager">3</p>
<p id="page4" class="pager">4</p>
<p id="page5" class="pager">5</p>
<p id="page6" class="pager">6</p>
<p id="page7" class="pager">7</p>
<div class="pull-right" id="btn_all">
<input class="btn active-btn" type="button" id="prev_btn" style="background-color:#66cdaa" style="width:70px;margin:1em" value="Prev.">
<div class="btn-group" id="btn-group">
<br>
<input class="btn butt active-btn" type="button" id="btn_page1" value="1">
<input class="btn butt" type="button" id="btn_page2" value="2">
<input class="btn butt" type="button" id="btn_page3" value="3">
<input class="btn butt" type="button" id="btn_page4" value="4">
<input class="btn butt" type="button" id="btn_page5" value="5">
<input class="btn butt" type="button" id="btn_page6" value="6">
<input class="btn butt" type="button" id="btn_page7" value="7">
<input class="btn butt" type="button" id="next_btn" value="Next">
</div>
I think you can just use a switch statement to test for the key :
document.onkeydown = (e) => {
switch (e.keyCode) {
case 37 :
prevPage(); break;
case 39 :
nextPage(); break;
}
}
I have written my own version of what you're trying to do (at least what I think you're trying to do), feel free to use that as an inspiration.
I use CSS3 transitions instead of jQuery's toggle.
const pagesCount = 7;
let currentPage = 1;
// ---- Generating buttons and pages
const $btnGroup = $("#btn-group");
const $pagesContainer = $("#pages");
for(let i=1; i<=pagesCount; i++){
$pagesContainer.append(`<div class='page'><h2>PAGE ${i}</h2></div>`);
$btnGroup.append(`<input type='button' value='${i}'/>`);
}
const $btns = $btnGroup.find("input")
$btns.first().addClass("active");
const $pages = $(".page");
$pages.not(":eq(0)").addClass("toRight");
// ---- End generating buttons
$btns.click( function() {
currentPage = +$(this).val();
changePage(currentPage);
});
changePage = (pageNum) => {
$pages.removeClass("toLeft toRight");
$pages.slice(0, pageNum-1).addClass("toLeft");
$pages.slice(pageNum, pagesCount).addClass("toRight");
updateButtons();
}
updateButtons = () => {
$btns.removeClass("active");
$btns.eq(currentPage-1).addClass("active");
}
nextPage = () => {
return currentPage===pagesCount ? null : changePage(++currentPage);
}
prevPage = () => {
return currentPage===1 ? null : changePage(--currentPage);
}
document.onkeydown = (e) => {
switch (e.keyCode) {
case 37 :
prevPage(); break;
case 39 :
nextPage(); break;
}
}
$("#prev_btn").click(prevPage);
$("#next_btn").click(nextPage);
#pages {
position: relative;
width: 400px;
height: 200px;
overflow: hidden;
}
#pages .page {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
color: #000;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-transition: all 0.3s ease-in-out;
transition: all 0.3s ease-in-out;
}
#pages .page:nth-child(even) {
background: #008000;
}
#pages .page:nth-child(odd) {
background: #00f;
}
#pages .page.toLeft {
-webkit-transform: translateX(-100%);
transform: translateX(-100%);
}
#pages .page.toRight {
-webkit-transform: translateX(100%);
transform: translateX(100%);
}
#pages .page h2 {
color: #fff;
}
nav {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
width: 400px;
}
nav input {
background-color: #66cdaa;
}
nav #btn-group input {
margin: 0 5px;
}
nav #btn-group input.active {
background: #00f;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pages"></div>
<nav>
<input class="btn active-btn" type="button" id="prev_btn" value="Prev.">
<div id="btn-group"></div>
<input class="btn butt active-btn" type="button" id="next_btn" value="Next">
</nav>
One could also imagine a solution where all the pages would be in a line, forming a ribbon, and the pagination buttons would just translate the whole ribbon to the right place, to show the correct page transform : translateX(n%)
I hope it helps.
Lately I've been trying to watch/study javascript and got interested in this certain program since I know I'll be able to use it a lot in the future.
I've seen a tutorial on youtube on how to "hide/show" a div so I tweaked it and made it "show/hide" div's and added two more div's. My problem is I wanted to hide other open div's when I want to show a specific one since my code now shows all of the div's regardless of the present ones.
<html>
<head>
<style type="text/css">
#hide_add_fname {
padding: 20px;
background: #f0f0f0;
width: 200px;
display: none;
}
#hide_edit_fname {
padding: 20px;
background: #f0f0f0;
width: 200px;
display: none;
}
#hide_delete_fname {
padding: 20px;
background: #f0f0f0;
width: 200px;
display: none;
}
</style>
<script type="text/javascript">
function toggle_add_fname(id) {
var divelement = document.getElementById(id);
if (divelement.style.display == 'block')
divelement.style.display = 'none';
else
divelement.style.display = 'block';
}
function toggle_edit_fname(id) {
var divelement = document.getElementById(id);
if (divelement.style.display == 'block')
divelement.style.display = 'none';
else
divelement.style.display = 'block';
}
function toggle_delete_fname(id) {
var divelement = document.getElementById(id);
if (divelement.style.display == 'block')
divelement.style.display = 'none';
else
divelement.style.display = 'block';
}
</script>
</head>
<body>
<table border='1'>
<tr>
<td colspan='3'>
<center>First Name</center>
</td>
</tr>
<td>
<button onclick="toggle_add_fname('hide_add_fname');">Add</button>
</td>
<td>
<button onclick="toggle_edit_fname('hide_edit_fname');">Edit</button>
</td>
<td>
<button onclick="toggle_delete_fname('hide_delete_fname');">Delete</button>
</td>
</tr>
</table>
<div id="hide_add_fname">
<form method='POST'>
<center>Add First Name:</center>
<br>
<center>
<input type='text'></input>
</center>
<br>
<center>
<input type='submit' value='Add'>
</center>
</form>
</div>
<div id="hide_edit_fname">
<form method='POST'>
<center>Edit First Name:</center>
<br>
<center>
<input type='text'></input>
</center>
<br>
<center>
<input type='submit' value='Edit'>
</center>
</form>
</div>
<div id="hide_delete_fname">
<form method='POST'>
<center>Delete First Name:</center>
<br>
<center>
<input type='text'></input>
</center>
<br>
<center>
<input type='submit' value='Delete'>
</center>
</form>
</div>
</body>
</html>
try this code
<html>
<head>
<style type="text/css">
#hide_add_fname {
padding: 20px;
background: #f0f0f0;
width: 200px;
display: none;
}
#hide_edit_fname {
padding: 20px;
background: #f0f0f0;
width: 200px;
display: none;
}
#hide_delete_fname {
padding: 20px;
background: #f0f0f0;
width: 200px;
display: none;
}
</style>
<script type="text/javascript">
function toggle_add_fname(id) {
var divelement = document.getElementById(id);
if (divelement.style.display == 'block')
divelement.style.display = 'none';
else{
divelement.style.display = 'block';
document.getElementById('hide_edit_fname').style.display='none';
document.getElementById('hide_delete_fname').style.display='none';
}
}
function toggle_edit_fname(id) {
var divelement = document.getElementById(id);
if (divelement.style.display == 'block')
divelement.style.display = 'none';
else
{
divelement.style.display = 'block';
document.getElementById('hide_add_fname').style.display='none';
document.getElementById('hide_delete_fname').style.display='none';
}
}
function toggle_delete_fname(id) {
var divelement = document.getElementById(id);
if (divelement.style.display == 'block')
divelement.style.display = 'none';
else{
divelement.style.display = 'block';
document.getElementById('hide_add_fname').style.display='none';
document.getElementById('hide_edit_fname').style.display='none';
}
}
</script>
</head>
<body>
<table border='1'>
<tr>
<td colspan='3'>
<center>First Name</center>
</td>
</tr>
<td>
<button onclick="toggle_add_fname('hide_add_fname');">Add</button>
</td>
<td>
<button onclick="toggle_edit_fname('hide_edit_fname');">Edit</button>
</td>
<td>
<button onclick="toggle_delete_fname('hide_delete_fname');">Delete</button>
</td>
</tr>
</table>
<div id="hide_add_fname">
<form method='POST'>
<center>Add First Name:</center>
<br>
<center>
<input type='text'></input>
</center>
<br>
<center>
<input type='submit' value='Add'>
</center>
</form>
</div>
<div id="hide_edit_fname">
<form method='POST'>
<center>Edit First Name:</center>
<br>
<center>
<input type='text'></input>
</center>
<br>
<center>
<input type='submit' value='Edit'>
</center>
</form>
</div>
<div id="hide_delete_fname">
<form method='POST'>
<center>Delete First Name:</center>
<br>
<center>
<input type='text'></input>
</center>
<br>
<center>
<input type='submit' value='Delete'>
</center>
</form>
</div>
</body>
</html>
I would use jquery for this. Since it'll take roughly few lines of code to achieve something like this. But anyways, here's what you could do.
Add a class called divs to all of your divs. And paste this code at the beginning of each of toggle functions.
var myElements = document.querySelectorAll(".divs");
for (var i = 0; i < myElements.length; i++) {
myElements[i].style.display = 'none';
}
You could have the above code in a function and run it at the beginning of your toggle functions, and I recommend you to do this to keep your code cleaner.
Anyways, what I am doing here is hiding every div at the beginning regardless of what was clicked. And then your code will just show the div that needs to be shown. I am not really good at javascript for DOM manipulation. Javascript experts correct me if I am wrong.
EDIT:
I missed the fact that you want to toggle it as well. Here's the updated code.
function hidedivs(){
var myElements = document.querySelectorAll(".divs");
for (var i = 0; i < myElements.length; i++) {
myElements[i].style.display = 'none';
}
}
function toggle_add_fname(id) {
var divelement = document.getElementById(id);
if(divelement.style.display == 'none'){
hidedivs();
}
if(divelement.style.display == 'block')
divelement.style.display = 'none';
else
divelement.style.display = 'block';
}
function toggle_edit_fname(id) {
var divelement = document.getElementById(id);
if(divelement.style.display == 'none'){
hidedivs();
}
if(divelement.style.display == 'block')
divelement.style.display = 'none';
else
divelement.style.display = 'block';
}
function toggle_delete_fname(id) {
var divelement = document.getElementById(id);
if(divelement.style.display == 'none'){
hidedivs();
}
if(divelement.style.display == 'block')
divelement.style.display = 'none';
else
divelement.style.display = 'block';
}
When you need to use the same specific selector more than once, classes are a better choice.
<div id="hide_add_fname" class='fname'>
A flexible way to apply style
var element_list = document.getElementsByClassName(class_name);
for (var i = 0; i < element_list.length; i++) {
element_list[i].style.display = 'none';
}
JSFiddle example
http://jsfiddle.net/83yrf4tx/
More information about IDs and Classes
In CSS what is the difference between "." and "#" when declaring a set of styles?
I'm using this to show/hide some divs, at the end I have a button to show the divs one by one.
How can I have a second button to show/hide all of them at once without messing too much with the HTML?
Basically each div contains an input field, so the user clicks the "Add one more" button to get an extra field. By default, all fields are hidden so I need a button to show them all at once (I have 14 divs to show/hide).
Any help will be appreciated.
Javascript
var counter = 0;
var numBoxes = 3;
function toggle4(showHideDiv) {
var ele = document.getElementById(showHideDiv + counter);
if(ele.style.display == "block") {
ele.style.display = "none";
}
else {
ele.style.display = "block";
}
if(counter == numBoxes) {
document.getElementById("toggleButton").style.display = "none";
}
}
HTML
<table>
<tr>
<td style="width: 150px;">
<div id="box1" style="display: none;">First</div>
</td>
<td style="width: 150px;">
<div id="box2" style="display: none;">Second</div
</td>
<td style="width: 150px;">
<div id="box3" style="display: none;">Third</div
</td>
</tr>
</table>
<input id="toggleButton" type="button" value="Add one more!" onclick="counter++; toggle4('box');">
Here's the basic functionality, though it needs some refinement:
var d = document,
table = d.getElementsByTagName('table')[0],
divs = table.getElementsByTagName('div'),
toggle = d.getElementById('toggleButton'),
allToggle = d.getElementById('allToggle'),
count = 0;
function toggles(){
var elem = divs[count];
elem.style.display = 'block';
count++;
}
toggle.onclick = function(){
toggles();
};
allToggle.onclick = function(){
if (allToggle.getAttribute('data-show') == 1){
for(var i=0,len=divs.length;i<len;i++){
divs[i].style.display = 'none';
allToggle.setAttribute('data-show',0);
allToggle.value = 'Show all';
}
}
else {
for(var i=0,len=divs.length;i<len;i++){
divs[i].style.display = 'block';
allToggle.setAttribute('data-show',1);
allToggle.value = 'Hide all';
}
}
}
JS Fiddle demo.
The above based on the following HTML:
<table>
<tr>
<td style="width: 150px;">
<div id="box1" style="display: none;">First</div>
</td>
<td style="width: 150px;">
<div id="box2" style="display: none;">Second</div>
</td>
<td style="width: 150px;">
<div id="box3" style="display: none;">Third</div>
</td>
</tr>
</table>
<input id="toggleButton" type="button" value="Add one more!" />
<input id="allToggle" type="button" value="Show all" />
have a button with a function that selects all of the divs by a class (that you'll have to add) and hides/shows them. If you just want one button you'll have to remember your state, which in the example below I do with a global.
<button id="showhideall">
$(document).ready(function(){
var allshowing = true;
$("#showhideall").click(function(){
alert(allshowing);
if(allshowing){
$(".foo").hide();
allshowing=false;
} else {
$(".foo").show();
}
});
});
var counter = 0;
var numBoxes = 3;
function toggle4(showHideDiv) {
var ele = document.getElementById(showHideDiv + counter);
if(ele.style.display == "block") {
ele.style.display = "none";
}
else {
ele.style.display = "block";
}
if(counter == numBoxes) {
document.getElementById("toggleButton").style.display = "none";
}
}
function toggle3(contentDiv) {
if (contentDiv.constructor == Array) {
for(i=0; i < contentDiv.length; i++) {
toggle2(contentDiv[i]);
}
}
else {
toggle2(contentDiv);
}
}
function toggle2(showHideDiv) {
var ele = document.getElementById(showHideDiv);
if(ele.style.display == "block") {
ele.style.display = "none";
}
else {
ele.style.display = "block";
}
}
<input id="toggleButton" type="button" value="Show me the money!" onclick="counter++; toggle4('box');">
<input type="button" value="Press me to toggle all 3 DIVs" onClick="toggle3(['box1', 'box2', 'box3']);">