So I'm building a form in HTML that makes use of a lot of checkboxes and hidden Divs. Right now I'm using
function HideDiv1() {
var checkBox = document.getElementById("Check1");
var div = document.getElementById("Div1");
if (checkBox.checked == true) {
div.style.display = "block";
} else {
div.style.display = "none";
}
}
<input type="checkbox" id="Check1">CheckBox to show Div1
<div id="Div1" style="display: none;">I should be hidden, assuming the author didn't mess up!</div>
To hide each div based on the appropriate checkbox. But this means that I am copying and rewriting this function every time and the section where I like to keep my functions is getting quite large. I was wondering if there was an easier way to do this such that I would only need one function and I could dynamically show and hide Divs without needing to copy and rewrite this function every time.
(If there is some easy JQuery solution to this: please keep in mind that I have no clue how to use JQuery)
This may be a duplicate, I saw the answer once before in the past but I have no idea how to find it again :(
You can use data attributes to identify which div to show when the checkbox is changed.
You can do this by listening for the change event on each checkbox and toggling the corresponding div with jQuery.toggle:
$('input[type=checkbox]').change(function(){
$('div[data-id='+$(this).data('target')+']').toggle()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" data-target="1">CheckBox to show Div1
<div style="display: none;" data-id="1">Div1</div>
<br/>
<input type="checkbox" data-target="2">CheckBox to show Div2
<div style="display: none;" data-id="2">Div2</div>
Vanilla JS implementation:
document.addEventListener('click', function(e){
if(e.target.matches('input[type=checkbox]')){
let target = document.querySelector('div[data-id="'+e.target.dataset.target+'"]');
target.style.display = target.style.display == "none" ? "block" : "none";
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" data-target="1">CheckBox to show Div1
<div style="display: none;" data-id="1">Div1</div>
<br/>
<input type="checkbox" data-target="2">CheckBox to show Div2
<div style="display: none;" data-id="2">Div2</div>
You would add an onchange attribute to the checkbox to call a single function called hideDiv and pass it two arguments that are the ids of the checkbox and the div that you are hiding with that checkbox:
onchange="hideDiv("check1","div1")"
...then hideDiv uses the arguments passed to it to toggle the correct div:
function hideDiv(checkId, divId) {
const checkbox = document.getElementById(checkId)
const div = document.getElementById(divId);
if (checkBox.checked == true) {
div.style.display = "block";
} else {
div.style.display = "none";
}
}
Get in the habit of using let for variables that you need to change and const for variables that will not change value instead of var.
Related
I have a textarea for the user to type something and it has a cancel and a submit button as part of it.
How can I make it so that the cancel and submit button only appears when the user clicks inside the textarea? (using javascript, no jquery please)
I have attempted using this javascript function:
function setButtons(writingtext) {
if (writingtext) {
document.getElementById('cfm').style.display = 'block';
document.getElementById('cancel').style.display = 'block';
}
else {
document.getElementById('cfm').style.display = 'none';
document.getElementById('cancel').style.display = 'none';
}
}
When the user clicks the text area, it would be onClick="setButtons(True)" -> displays the buttons.
I'm not sure if this is the right approach here. Sorry, really new to this.
Any help would be appreciated!
You have control over your html you can do it with just css sniping the next sibling at :focus like this:
div {display:none;}
textarea:focus + div {display:block;}
<textarea name="" id="" cols="30" rows="10"></textarea>
<div>
<input type="submit">
<input type="submit">
</div>
This is only a simple example to show the buttons on focus. If you want to hide them, I think you will be able to manage that solution.
If all you want to do is show the buttons when the text area is focused, use the CSS-only solution. However, I'm guessing you'll want to keep them for a bit or do some extra pre-processing before the submit, in which case you should use the javascript option.
document.querySelector("#textarea").addEventListener("focus", function() {
document.querySelector("#submit").style.display = "block";
document.querySelector("#cancel").style.display = "block";
});
button {
display: none;
}
<textarea id="textarea"></textarea>
<button id="submit">Submit</button>
<button id="cancel">Cancel</button>
You can just assign an id to the textarea for example text and then use
document.getElementById('text').addEventListener('focus', function(){
document.getElementById('cfm').style.display = 'block'
document.getElementById('cancel').style.display = 'block'
})
// Hide when blur (when not focused)
document.getElementById('text').addEventListener('blur', function(){
document.getElementById('cfm').style.display = 'none'
document.getElementById('cancel').style.display = 'none'
})
You should use
onfocus="setButtons(this)" instead of onClick
function setButtons(writingtext) {
document.getElementById('cfm').style.display = 'block';
document.getElementById('cancel').style.display = 'block';
}
I want show div 1 on html load while hiding div 2, then using onclick I want to exchange their visibility like when clicking button hide div1 then show div2, then when clicking again, hide div2 then show div 1. Here is my code:
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'none')
e.style.display = 'block';
else
e.style.display = 'none';
}
Hide DIV 1 show DIV 2
<div id="foo"> This is DIV 1</div></div>
<div id="foo"> This is DIV 2</div></div>
Initially set your div1 to display:none; and simply toggle them.
I have used class targetElement just to get rid of common selector. hidden class is used to use the default style display:none; and to replace the inline-style.
I woul like to use button instead of Click here. to do this simple replace a tag with <button type="button"> Button Name </button>
$('#toggleButton').on('click',function(){
$('.targetElement').toggleClass('hidden');
});
.hidden{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="toggleButton" href="#">Click here</a>
<div id="foo" class="targetElement hidden"> This is DIV 1</div></div>
<div id="foo" class="targetElement"> This is DIV 2</div></div>
The attribute id must be unique in a document. Use class instead.
First use CSS to hide the second div. Then use forEach() to hide/show div. You should also avoid using inline event handler.
Try the following way:
document.querySelector('a').addEventListener('click',function(){
[].forEach.call(document.querySelectorAll('.foo'), function(el){
if(el.style.display == 'none')
el.style.display = 'block';
else
el.style.display = 'none';
});
});
Hide DIV 1 show DIV 2
<div class="foo"> This is DIV 1</div></div>
<div class="foo" style="display:none;"> This is DIV 2</div></div>
It is not good practice to have 2 elements with the same ID. ID's should always be unique. Use classes instead. To hide a div onload. Simply add the css to your html element in a style attribute. You also had unecessary </div> tags that I removed.
Here is working code using JQuery (less code) :
$("#toggle").on("click", function() {
$(".isToggable").toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="toggle" href="#" >Hide DIV 1 show DIV 2</a>
<div class="isToggable"> This is DIV 1</div>
<div class="isToggable" style="display:none"> This is DIV 2</div>
In the html, I added classes to elements that you want to be toggled. I also added an ID to the a tag. In the JQuery I added an event listener onclick on that a tag using it's ID. $(".isToggable").toggle(); takes all the elements with the class "isToggable" in the page toggles their visibility.
With no parameters, the .toggle() method simply toggles the visibility of elements
More information on toggle : JQuery Toggle
Old answer (vanilla javascript)
function toggle_visibility(id) {
var container = document.getElementById(id);
for (var i = 0; i < container.children.length; i++) {
let currentElem = container.children[i];
if (currentElem.style.display === "none") {
currentElem.style.display = "block";
} else {
currentElem.style.display = "none";
}
}
}
Hide DIV 1 show DIV 2
<div id="container">
<div> This is DIV 1</div>
<div style="display:none"> This is DIV 2</div>
</div>
How this works is you put your elements that you want to toggle the visibility inside a container and the toggle_visibility function will toggle all the visibilities of the elements inside. That way if you decide to add more div's they will all be handled.
If you have any questions on how this works. Don't hesitate to ask. Hope it helps !
I would like to change display property of this input (actually of div which contains it) after onclick ("Click here"). This part goes well ... but after clicking again I want it to be hidden again (has display="none" instead of "block" again and so on) and here I have difficulties.
I've tried classList.toggle but ... I' don't want to change classes, I want to change just one property. I know there is also possibility of creating my input field by using Javascript but I presume I'll come to a deadlock again in the same point.
<form role="form">
<p id="mag">Click here!</p>
<div id="switch" class="xxx"style="display:none;" >
<input id="sr"class="offf" autocomplete="off" placeholder="Search" type="text" >
</div>
</form>
document.getElementById("mag").addEventListener("click", function toffi(){
document.getElementById("switch").style.display="block";
console.log(document.getElementById("switch").style.display);
});
http://codepen.io/zeeebra/pen/RgRYxK
Try this:
document.getElementById("mag").addEventListener("click", function toffi(){
var sw = document.getElementById("switch");
if (sw.style.display === "block") {
sw.style.display = "none";
} else {
sw.style.display = "block";
}
console.log(sw.style.display);
});
How do I show a div (with classname) that is closest to my inputbox?
I have several inputboxes so i just need to display the specific inputbox.
In my example i want to show a div box above the input ( showing that the inputbox has wrong content i.e Numbers and not Letters ) if the inputbox has letters, the div must hide again.
So it should be a normal error report.
My Code is following:
https://jsfiddle.net/1mvb3wko/
function calculate(){
var regex = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?()]/);
var letter = /[a-zA-Z ]+/;
error1 = false;
error2 = false;
error3 = false;
var input = ['ID1','ID2'];
var element;
for(i=0;i <element.length; i++{
element = document.getElementById(input[i]);
if(regex.test(element.value) && letter.test(element.value)){
element.style.border = '4px solid red';
//Here's where i'm stuck
//i'm trying to SHOW the previous Div with class(Errorreport) if the input is wrong
//$(element).prev('.Errorreport').show(); doesn't work
}
}
}
Since there are already answers talking about the use of .closest I;m going to take a different approach and suggest that you remove all of those unnecessary <div> elements and focus on what you want to achieve. You want an error message to be displayed when the user types something wrong in one of the inputs.
You are better of using spans or labels, those are the elements that are often used to display form errors.
So you want a way to select all inputs. All of them have a .form-control class so you can use jQuery:
$('.form-control')
Watch for the change or blur events, whatever suits your needs and use jQuery's .parent() and .find() to find the error message and show it.
I changed a lot of your code to be cleaner and more descriptive of what it does:
https://jsfiddle.net/uf72taeu/2/
What you expected is there, just change if condition. By default I made it true.
function calculate(element) {
var regex = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?()]/);
var letter = /[a-zA-Z ]+/;
var inputBox = $(element);//$('#'+input[i]);
if (true/* regex.test(element.value) && letter.test(element.value) */)
{
var par = inputBox.parent(); // will return enclosed div
par = par.parent();// will return div with class 'row'
var errReport = par.prev(); // will return previous div, which is div with class 'row Errorreport'
// do whatever in errReport
errReport.css("display", "block");
inputBox.css("border", "4px solid red");
}
// }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row Errorreport" style="display: none;">
<div>Error id 1</div>
</div>
<div class="row">
<div>
<input class="autoausgabe form-control " id="ID1"
onChange="calculate(this);">
</div>
</div>
<div class="row Errorreport" style="display: none;">
<div>Error id 2</div>
</div>
<div class="row">
<div>
<input class="autoausgabe form-control " id="ID2"
onChange="calculate(this);">
</div>
</div>
I am developing a site where I can NOT use jQuery (please, no comments on how good is it, it's prohibited) and I need to reproduce something like .toggle() just for show/hide a div with a class.
I've a group of boxes with a arrow, this arrow can expand a submenu. Let's see an example:
<div class="box">
<div class="box-utils">
</div>
<h2>Example case</h2>
<div class="box-submenu hidden">
<ul />
</div>
</div>
I need that click on the <a /> inside the <div class="box-utils" /> shows/hide the box-submenu class. When it's hidden, the <a /> needs to have class="down", when it's not hidden it needs to be class="up". This also needs to work with more than one case in the same page.
Can someone help me?
Thank you in advance!
Create a toggle function like the one below, provide an id attribute on your DIV (call it box-submenu or something) and call the function from your anchor, and use the ID to lookup whatever you want to hide/show.
<script language="javascript">
function toggle() {
var ele = document.getElementById("box-submenu");
var link = document.getElementById("linkId");
if(ele.style.display == "block") {
ele.style.display = "none";
link.className = "down";
}
else {
ele.style.display = "block";
link.className = "up";
}
}
</script>