Toggle Hide/show upon clicking a checkbox and hitting submit button javascript - javascript

I am trying to use checkboxes and a submit button to toggle hide/show a section of my resume. I have two sections, education and work experience. I have the code to set up the checkboxes and submit button but I am not sure how to code what comes after it to make the checkboxes work. this is what I have:
<script>
function validateCheckbox() {
var checkbox = document.getElementsByName("c1");
for (var i=0; i < checkbox.length; i++) {
if (radios[i].checked) {
return true;
}
}
function myFunction() {
var x = document.getElementById("workexperience");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
I want to toggle the visibility of an element by id in CSS and I want to have the information be hidden upon page load so that if a site visitor clicks on the checkbox that says work experience and then hits the submit button it will show the relevant section either education for one checkbox or work experience for the other.

HTML
<div id="wrapper">
<div>
<input type="radio" name="resume" value="work-experience">
<input type="radio" name="resume" value="education">
<button type="button" id="view-resume">View</button>
</div>
<div id="work-experience" class="display-none">Work Experience</div>
<div id="education" class="display-none">Education</div>
</div>
CSS
<style type="text/css">
.display-none{
display: none;
}
</style>
JAVASCRIPT
<script type="text/javascript">
document.getElementById('view-resume').addEventListener("click", function(){
var resume = document.querySelector('input[name = "resume"]:checked').value;
document.getElementById(resume).style.display = 'block';
if(resume == 'work-experience'){
document.getElementById('education').style.display = 'none';
}else{
document.getElementById('work-experience').style.display = 'none';
}
});
</script>

Related

Make id ex disappear if you click anywhere outside of it

I'm trying to figure out how I can make a targeted element disappear. If you click any where that is outside of that element. I have created a toggle effect with a button but I want to also hide id ex if there is any clicks outside of ex. I have
found working sources on this subject but it's based on jQuery most of the time. I have nothing against jQuery I just need to do this in pure JS structure for
personal reasons.
<!DOCTYPE html>
<html>
<head>
<style>
#ex{
display: none;
}
</style>
<script>
document.addEventListener('DOMContentLoaded',function(){
var b= document.getElementsByTagName('button')[0];
b.addEventListener('click',fx);
function fx() {
var x = document.getElementById("ex");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
});
</script>
</head>
<body>
<button>Toggle</button>
<h1 id="ex">Blablablablabla bla bla JS</h1>
</body>
</html>
UPDATE
Any time I tried to ask this question on this topic on many sites nobody never understand what I mean. In other words I don't want the body to do any toggling just the button the best way I can explain this is like this you know how in some applications if you click on a drop down menu and you click out side of that drop down menu then it disappears but you can use the navigation bar button to bring it back? That's what i'm trying to do .
I want something like this but in pure JS structure.
<style>
#ex{
display: none;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#ex').click(function(execute){
execute.stopPropagation();
});
$('button').click(function(execute) {
execute.preventDefault();
execute.stopPropagation();
$('#ex').toggle();
});
$(document).click(function() {
$('#ex').hide();
});
});
</script>
<button>Toggle</button>
<h1 id='ex'>Blablablablabla bla bla JS</h1>
<!DOCTYPE html>
<html>
<head>
<style>
#ex{
display: none;
}
</style>
<script>
document.addEventListener("click", function(obj){
var x = document.getElementById("ex");
if(obj.target.id != "ex") {
if (x.style.display === "block") {
x.style.display = "none";
} else if(obj.target.id == "btn") {
x.style.display = "block";
}
}
});
</script>
</head>
<body>
<button id="btn">Toggle</button>
<h1 id="ex">Blablablablabla bla bla JS</h1>
</body>
</html>
Update
You can save the button id and compare it with the clicked element id.
var b= document.getElementsByTagName('button')[0];
var btnId = b.getAttribute('id');
document.addEventListener('click',fx);
function fx(e) {
var x = document.getElementById("ex");
if (e.target.getAttribute('id') == btnId) {
if(x.style.display == "block")
x.style.display = "none";
else
x.style.display = "block";
}
else{ // we did not click on button
if (e.target.getAttribute('id') != 'ex')
x.style.display = 'none';
}
}

Javascript's getElementsByClassName() is unable to find proper classes

I've been trying to do a simple form setup with tabs using a guide from: https://www.w3schools.com/howto/howto_js_form_steps.asp.
I have three divs with class="tab" inside a form, which I am trying to make visible/invisible using javascript:
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";
}
This is supposed to display the n'th tab but no tabs are visible when the page is loaded, moreover, both buttons (previous and next, see code below) are visible when the page is loaded and n = 0; I have tried to get this to work with different setups using:
<script> // code goes here </script>
or simply including a separate .js file, embedding the script section into, head, body, html or even the form has been unsuccessful. All the while, I can run simple js commands at the start of the same script section, like: alert("test");.
I am running the page on a Linux machine with a premade Bitnami LAMP stack.
<!Doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles/login.css" />
<link rel="stylesheet" href="styles/main.css">
<link rel="stylesheet" href="styles/new_user.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<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 = "Submit";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
//... and run a function that will display the correct step indicator:
fixStepIndicator(n)
}
function nextPrev(n) {
// This function should figure out which tab to display
var x = document.getElementsByClassName("tab");
// 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 submitted:
document.getElementById("register_form").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
// This manages step indicators.
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 to the current step:
x[n].className += " active";
}
</script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body class="background">
<main class="wrapper">
<div id="parent">
<form id="register_form" action="" method="post">
<h1>New user:</h1>
<div style="text-align:center;">
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
</div>
<div style="float:right; padding: 15px;">
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
</div>
<div style="float:left; padding: 15px;">
<button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
</div>
<div class="tab">
//content
</div>
<div class="tab">
//content
</div>
<div class="tab">
//content
</div>
</div>
</form>
</div>
</main>
</body>
</html>
The tab class itself looks like and should be invisible by default:
.tab {
display: none;
}
I would like to find out why it is that the tabs in the form do not seem to be influenced by the showTab function. I've been at this issue for hours and I am absolutely clueless, any help would be appreciated!
Kind regards.
First problem with your code, is that the javascript is running before the page is loaded. Therefore it will not work. You must wait for the page to load before you call your function. There are several ways to to that, usually with a library.
In pure javascript you can listen for the event DOMContentLoaded on the document, something like this:
<script>
var currentTab = 0; // Current tab is set to be the first tab (0)
function showTab(n) {
// This function will display the specified tab of the form...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
}
document.addEventListener("DOMContentLoaded", function(event) {
// this code will be running when the document is loaded
showTab(currentTab); // Display the current tab
});
</script>
I am not sure if this is 100% accurate, but the code below shows several improvements to your code.
I prefer querySelectorAll since I can pass in any CSS selector.
I used forEach to walk through the tabs and steps.
I only get the tabs once since that doesn't ever change.
But I wasn't 100% sure what the CSS did so I can't guarantee that this code is exactly what you need.
To make this work you must place the <script> after all your HTML. Place it as the last child in the <body>. don't call showTabs the first time until body.onload
var currentTab = 0; // Current tab is set to be the first tab (0)
var tabs = document.querySelectorAll(".tab");
showTab(currentTab); // Display the current tab
function showTab(n) {
tabs.forEach(
function(tab, i) {
// This function will display the specified tab of the form...
tab.style.display = n===i ? 'block' : 'none';
}
);
//... and fix the Previous/Next buttons:
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (tabs.length - 1)) {
document.getElementById("nextBtn").innerHTML = "Submit";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
//... and run a function that will display the correct step indicator:
fixStepIndicator(n)
}
function nextPrev(n) {
// Hide the current tab:
tabs[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 >= tabs.length) {
//...the form gets submitted:
document.getElementById("register_form").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
// This manages step indicators.
function fixStepIndicator(n) {
// This function removes the "active" class of all steps...
var steps = document.querySelectorAll(".step");
if (steps) {
steps.forEach(
function(step, i) {
step.classList.toggle("active", n === i);
}
);
}
}
<main class="wrapper">
<div id="parent">
<form id="register_form" action="" method="post">
<h1>New user:</h1>
<div style="text-align:center;">
<span class="step">Step1</span>
<span class="step">Step2</span>
<span class="step">Step3</span>
</div>
<div style="float:right; padding: 15px;">
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
</div>
<div style="float:left; padding: 15px;">
<button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
</div>
<div class="tab">
//content 1
</div>
<div class="tab">
//content 2
</div>
<div class="tab">
//content 3
</div>
</div>
</form>
</div>
</main>

how do I use the same link to "re-hide" previously hidden text via Javascript?

The below code snippet shows the invite code when I click "Invite Code". But how do I re-hide the invite code if the same link is clicked again? And can it be done where it cycles back and forth with subsequent clicks? I didn't write this code but merely modified it to my use. I am still very new to this type of thing. Thanks!
<style>
div.hide { display:none; }
div.show { text-align:center; }
</style>
<script type='text/javascript'>
function showText(show, hide) {
document.getElementById(show).className = "show";
document.getElementById(hide).className = "hide";
}
</script>
<br>
<font color="red">-</font>Home<font color="red"> / </font><a onclick="showText('text1')" href="javascript:void(0);">Invite Code</a>-</font>
<div id="text1" class="hide"><font color="red">abc123</font></div>
</center></h3>
Simply use this function:
function showText(id)
{
var elem = document.getElementById(id);
if(elem.style.display == 'none')
{
elem.style.display = 'inline';
}
else
{
elem.style.display = 'none';
}
}
<a onClick="showText('text1');" href="#">Show or Hide</a><br/>
<div style="height: 30px;"><div id="text1" style="display: none;">Text to hide or show... WTF?!</div></div>
<div>This text should not move.</div>
PS: This also works for 2 Elements...
Greetings
I really don't see the use for the show class. You could just toggle the hide class on the elements that you want to toggle.
Assume you dont need the show class, then use the classList.toggle function like this
function toggle(target){
document.getElementById(target).classList.toggle('hide');
}
.hide{ display:none }
<button onclick="toggle('test')">Show / Hide</button>
<div id="test" class="hide">Hello world!</div>
save the state with a boolean
var hided = true;
function showText(show,hide){
if (hided){
document.getElementById(show).className = "show";
document.getElementById(hide).className = "hide";
}
else{
document.getElementById(show).className = "hide";
document.getElementById(hide).className = "show";
}
hided = !hided;
}
fiddle with this code and some of your html : fiddle,
isn't it the expected behavior ?
<html>
<div ID="content" style="display:block;">This is content.</div>
<script type="text/javascript">
function toggleContent() {
// Get the DOM reference
var contentId = document.getElementById("content");
// Toggle
contentId.style.display == "block" ? contentId.style.display = "none" :
contentId.style.display = "block";
}
</script>
<button onclick="toggleContent()">Toggle</button>
</html>
//Code is pretty self explanatory.

Toggling multiple divs with one link Javascript

so, ive got 2 divs, one which is visible from start, and the other is hidden. Im trying to work out the action so that when i click a single link, the first div disappears and the second appears, and to reverse on second click. I have some knowledge of javascript, but zero knowledge of Jquery and those were the only questions i could find on here.
<script language="javascript">
function toggle() {
var ele = document.getElementById("toggleContent");
var text = document.getElementById("displayContent");
if(ele.style.display == "block") {
ele.style.display = "none;
text.innerHTML = "blog posts";
}
else {
ele.style.display = "block";
text.innerHTML = "hide posts";
}
}
</script>
this is what i have so far, which works for one div, but i dont know how to change this to work for 2 divs through the same link
You are missing a quote, add a second quote like below:
ele.style.display = "none";
Use a class rather than an ID.
<style type="css/stylesheet">
#div1 {
width:200px;
height:100px;
background:green;
}
#div2 {
width:200px;
height:100px;
background:red;
}
.toggle {
display:none;
}
</style>
<div id="menu">Toggle
</div>
<div id="div1" class="toggle">
<p class="displayContent">I'm some content 1</p>
</div>
<div id="div2" class="toggle">
<p class="displayContent">I'm some content 2</p>
</div>
<script language="javascript">
var a = document.getElementById("link");
a.onclick = function () {
var ele = document.getElementsByClassName("toggle");
for (var i = 0; i < ele.length; i++) {
var item = ele[i];
if (item.style.display == "block") {
item.style.display = "none";
} else {
item.style.display = "block";
item.innerHtml = "some content from " + i;
}
}
};
</script>
Here is the JSFiddle solution http://jsfiddle.net/dUU7j/

Use link click to clear input field Javascript

I am trying to use a link to clear a text input field. I am hiding and showing a memo field and and if the user puts text in the field and clicks "remove memo" link I want to text field to clear on click.
<html>
<head>
<script language="JavaScript">
function toggle(id) {
var state = document.getElementById(id).style.display;
if (state == 'block') {
document.getElementById(id).style.display = 'none';
} else {
document.getElementById(id).style.display = 'block';
}
}
oldTextAry = new Array();
function changeText (fieldObj, newTexStr) {
if (newTexStr == fieldObj.innerHTML) {
fieldObj.innerHTML = oldTextAry[fieldObj.id];
} else {
oldTextAry[fieldObj.id] = fieldObj.innerHTML;
fieldObj.innerHTML = newTexStr;
}
}
</script>
<style type="text/css">
<!--
#hidden1 {display: none;}
-->
</style>
</head>
<body>
<a href="###" onclick="toggle('hidden1'); changeText(this,'Remove Memo');" class="memo" >Add Memo</a>
</div>
<div id="hidden1"><div class="memo">Memo: <input type="text" id="ctlWorkflow_ctlMemo381" size="45" maxlength="32" name="ctlWorkflow:ctlMemo381"></div> </div>
</body>
</html>
I am stuck and cannot get the field to clear.
Use the below code in the click delegate. Sorry for the mistaken answer.
document.getElementById("ctlWorkflow_ctlMemo381").value = '';
Cheers

Categories