How to change div contents with javascript - javascript

This seems simple but I don't know what I'm doing really. I have 2 radio buttons and depending on which one is selected the contents of a div will change. Right now I have 2 divs inside a parent div but it would just hide one div and show the other. This wouldn't be bad if they didn't take up space even when they're invisible.
HTML:
<div>
<form role="form">
<div>
<div class="radio" id="radioSelection" onchange="chooseDiv()">
<label>
<input type="radio" name="optradio" id="selectionDiv1" checked />Choose Div1
</label>
<label>
<input type="radio" name="optradio" id="selectionDiv2" />Choose Div2
</label>
</div>
</div>
</form>
</div>
<div id="parentDiv">
<div id="div1">You're Awesome!</div>
<div id="div2">Everybody loves you!</div>
</div>
JavaScript:
function chooseDiv() {
if (document.getElementById("selectionDiv1").checked) {
document.getElementById("div2").style.visibility = "hidden";
document.getElementById("div1").style.visibility = "visible";
} else {
document.getElementById("div2").style.visibility = "visible";
document.getElementById("div1").style.visibility = "hidden";
}
}
So I'd like to have it so only one div is visible at a time depending on which radio button is checked, and don't have them take up space when they're not in the div. Thanks!

If you want those divs to stop taking space, you have to use display:none instead of visibility:hidden, change your function to
function chooseDiv() {
if (document.getElementById("selectionDiv1").checked) {
document.getElementById("div2").style.display = "none";
document.getElementById("div1").style.display = "block";
} else {
document.getElementById("div2").style.display = "block";
document.getElementById("div1").style.display = "none";
}
}
Working plnkr: http://plnkr.co/edit/H4C9C7dAD324qJUgESMF?p=preview

visibility property will always use the space whenever it is hidden.
Better approach would be to use display property.
Something like this:
document.getElementById("div2").style.display= "none"; //similar to hidden
document.getElementById("div1").style.display= "block"; // visible

You are using visibility: hidden to hide the divs, which hides them but let them take space in the browser, try instead the display property, instead of using hidden use none, and instead of using visible use block.

You have to understand first the difference between the display and visibility properties.
display - none - when you do display none that means whole element from DOM will hide with its physical existence in DOM.So, there will be no space allocation for that element in DOM.
Visibility - hidden - In this case , you are hiding only that element but physically that element is present in that space.So, space will be allocate that element.
for more details please follow this

Using just one div and change content
DEMO
HTML
<body onload='chooseDiv();'>
<div>
<form role="form">
<div>
<div class="radio" id="radioSelection" onchange="chooseDiv()">
<label>
<input type="radio" name="optradio" id="selectionDiv1" checked />Choose Div1
</label>
<label>
<input type="radio" name="optradio" id="selectionDiv2" />Choose Div2
</label>
</div>
</div>
</form>
</div>
<div id="parentDiv">
<div id="div1"></div>
</div>
<div style='display:none'>
<div id='c1'><span>TEST 1</span><img src='http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon#2.png?v=hiFacebook'/></div>
<div id='c2'><span>TEST 2</span><img src='http://zelcs.com/wp-content/uploads/2013/02/stackoverflow-logo-dumpster.jpg' /></div>
</div>
</body>
JS
function chooseDiv() {
var div = document.getElementById("div1");
var msg = document.getElementById("c1").innerHTML;
if (!document.getElementById("selectionDiv1").checked) {
msg = document.getElementById("c2").innerHTML;
}
div.innerHTML = msg;
}

Related

Javascript Function that shows and hides Div based on Checkboxes Dynamically

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.

Javascript - Show a div section set as hidden

I know there are A LOT of Qs on hiding-showing a div: I tried them all but somehow nothing seems to work.
I have a form and on loading the page div 1 shows. Once user hits the "Next" button then div 2 (previously not displayed) needs to show. What I would need help with is get the div 2 displayed upon click of the Next button
here is one of my many attempts:
<div>
table 1
</div>
<button name="next" onclick="javascript:showDiv();"> Next </button>
<script type="text/javascript">
function showDiv() {
div = document.getElemntById('dynamic');
div.style.visibility = "visible";
}
</script>
<div id="dynamic" style="display:none">
table 2
<input type="submit" value="Submit"/>
</div>
</form>
</body>
If anyone at all could help me I would be most grateful!! Thank you
You need to switch between "display:none" and "display:block" to hide and show the div.
Also you function should be document.getElementById instead of document.getElemntById
function showDiv() {
div = document.getElementById('dynamic');
div.style.display = "block";
}
<button name="next" onclick="javascript:showDiv();"> Next </button>
<div id="dynamic" style="display:none">
table 2
<input type="submit" value="Submit"/>
</div>
Confusingly, display: none can't be cancelled out by setting visibility to visible. The display property determines how the layout engine positions the div, and the visibility property determines whether it is rendered. So if you start off the div with
<div id="dynamic" style="visibility:hidden">
It should work fine. I generally don't recommend hiding stuff using display: none because it forces the browser to re-layout the window which can move elements around. Using visibility means that everything stays still.
if(document.getElementById("div1").style.display == "none")
{
document.getElementById("div1").style.display = "";//show it
}
else
{
document.getElementById("div1").style.display = "none";//hide it
}

Custom keyboard tab order in html4

I want to manage keyboard tab order functionality, I am using a template for header, footer and sidebar where many anchor element & input element exists. In template content we can not put and tabindex attribute which is not in my control.
Middle part of template is my work area, where I created a form and some element
<fieldset id="myWorkArea">
<div class="fieldrow">
<label for="input1">Class</label>
<input id="input1"/>
<a id="help1" href="#">what's this?</a>
</div>
<div class="fieldrow">
<label for="input2">Class</label>
<input id="input2"/>
<a id="help2" href="#">what's this?</a>
</div>
</fieldset>
In above code I want to cursor tabbing in below id order.
#help1 > #input1
#help2 > #input2
Is any approach to control keyboard tabbing order in only #myWorkArea fieldset elements as we can not put tabindex for all element in page?
Even if you have no access to the template, you can still add the tabindex attribute programmatically.
Here you have a snippet:
var tabindex = 1;
$('#myWorkArea .fieldrow').each( function() {
$('a', this).attr('tabindex', tabindex++);
$('input', this).attr('tabindex', tabindex++);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset id="myWorkArea">
<div class="fieldrow">
<label for="input1">Class</label>
<input id="input1"/>
<a id="help1" href="#">what's this?</a>
</div>
<div class="fieldrow">
<label for="input2">Class</label>
<input id="input2"/>
<a id="help2" href="#">what's this?</a>
</div>
</fieldset>
Hope it helps!
You can add the tab index programmatically using javascript as David mentioned in his answer.
Or If you want you can control the taborder functionality by binding your own event to only these elements like below code.
Working FIDDLE
$(function(){
var inputs = $('a#help1, a#help2,input#input1, input#input2');
$(inputs).bind('keydown', function (e) {
var self = $(this), form = self.parents('form:eq(0)'), focusable, next;
//check keycode for tabbing
if (e.keyCode == 9) {
switch($(this).attr("id")){
case "help1":
next=$('#input1');
break;
case "help2":
next=$('#input2');
break;
case "input1":
next=$('#help2');
break;
case "input2":
next=$('#help1');
break;
}
next.focus();
e.preventDefault();
return false;
}
});
});

How to select input content if there is only one error class

I want to check if there is only one div with an error class. And if so, I want to .select() the content of the input (that's in the in corresponding input class div).
How would I do such thing?
My attempt which does not work:
if($("div.addition").hasClass(".error").length === 0) {
(this).parent().find('input').select();
}
HTML
<form>
<div class="input">
<input type="text">
<div>
<div class="addition">Message message.</div>
</div>
</div>
<div class="input">
<input type="text">
<div>
<div class="addition">Message.</div>
</div>
<div class="input">
<!-- So in this case this input's content will be selected -->
<input type="text">
<div>
<div class="addition error">Error message.</div>
</div>
</div>
</form>
Here's a jsFiddle that should do it - I mentioned as a comment to your post that you're missing a </div> tag, that is fixed in the fiddle - without it, the jquery selector matches two inputs. Outline of the js:
if ($('div.error').length === 1) {
errorContent = $('div.error').parents('div.input').find('input').val();
alert(errorContent);
}
Here's a plain JavaScript implementation. No need to use jQuery unless you're already using it.
var errors = document.getElementsByClassName('error');
if(errors.length === 1){
//If there is one class with error
var content = errors[0].innerHTML;
} else{
//there is more than one error class.
}
I want to check if there is only one div with an error class.
if ($("div.error").length === 1) {
// Exactly one div with the class "error"
}
else {
// Zero or more than one
}
By using jQuery it can be done like:
$(document).ready(function(){
var div = $('.error');
if(div.length){
var val = div.parents('.input:first').find('input').val();
//val is the value of input
}
});

Hide/show div with javascript

I would like to show a form field textbox only when a certain checkbox is checked, and hide it when it is unhecked. I have gotten the code to make it hide when I check the box, but the textbox is displayed when the page is loaded until I check the box, which is opposite of what I would like to accomplish. I am pretty newbish with javascript so I am sure this is pretty elementary. Thanks for any help.
HTML:
<input type="checkbox" onclick="ShowCCFields(this.value);" name="CAT_Custom_510969" id="CAT_Custom_510969_7" value="Other..." />
Other...
<div class="item" id="other">
<label for="CAT_Custom_510972">Other:</label><br />
<textarea onkeydown="if(this.value.length>=4000)this.value=this.value.substring(0,3999);" class="cat_listbox" rows="4" cols="10" id="CAT_Custom_510972" name="CAT_Custom_510972"></textarea>
</div>
javascript:
// Hide or show textarea if the other checkbox field is checked
var voucher = document.getElementById("CAT_Custom_510969_7");
function ShowCCFields(val) {
if (!document.getElementById('other'))
return;
if (val == voucher.checked)
document.getElementById('other').style.display = 'inline';
else
document.getElementById('other').style.display = 'none';
}
Why not set the display to none to begin with? You can do that in CSS or just add it to
<div class="item" id="other" style="display: none;">
Set the style to none in the HTML, just like you do in the javascript:
<div class="item" id="other" style="display:none;">
Set Display to none in the control you want to hide :
<div class="item" id="other" style="display: none;">
And In your js Function :
document.getElementById('other').style.display = 'inline';

Categories

Resources