Hiding multiple form fields using checkboxes - javascript

I have this code that I need to edit so I can use it on multiple chkBox's and txtBox's.
Currently I can only hide one input field with one check box.
I know HTML and CSS but I am not familiar with JS.
I would like to be able to add a number at the end of each ID.
chkBox1, chkBox2, chkBox3... txtBox1, txtBox2, txtBox3...
Do I need to change getElementById to getElementsByTagName()?
JSFIDDLE for some reason it does not work here...?
This is my current code which hide the text field unless the checkbox is checked:
function showHide(){
var chkBox = document.getElementById("chkBox");
var txtBox = document.getElementById("txtBox");
if (chkBox.checked){
txtBox.style.visibility = "visible";
} else {
txtBox.style.visibility = "hidden";
}
}

The reason your code wasn't working is because it was running onLoad. Your DOM and the onclick were created before the load was complete. You could just move your code into your <head></head> tags and it will work as is. See here, all I did was select the "No wrap - in head", no code changes.
You could also continue to have your javascript run onLoad and remove your onclick and add an eventlistener in the javascript like this:
JSFiddle
var txtBox = document.getElementById("txtBox");
document.getElementById("chkBox").addEventListener("click", function() {
if (this.checked) {
txtBox.style.visibility = "visible";
} else {
txtBox.style.visibility = "hidden";
}
});
If you have multiple instances of this, I would change your DOM a bit sort of like this:
<form>
<div class="option">
<input type="text" name="txtBox1" class="hiddenInput" />
<br/>
<input type="checkbox" name="chkBox1" id="chkBox1" class="showHideCheck" />
<label for="chkBox1">Click me to show the text box</label>
</div>
<div class="option">
<input type="text" name="txtBox2" class="hiddenInput" />
<br/>
<input type="checkbox" id="chkBox2" name="chkBox2" class="showHideCheck" />
<label for="chkBox2">Click me to show the text box</label>
</div>
</form>
and do your JQuery like this (since you previously tagged jquery):
$(".hiddenInput").hide();
$(".showHideCheck").on("change", function() {
$this = $(this);
$input = $this.parent().find(".hiddenInput");
if($this.is(":checked")) {
$input.show();
} else {
$input.hide();
}
});
JSFiddle
Or with pure javascript and the similar DOM as above:
var checkBoxes = document.getElementsByClassName("showHideCheck");
for (var i = 0; i < checkBoxes.length; i++) {
checkBoxes[i].addEventListener('click', function () {
var txtBox = getAssociatedTextBox(this);
if (this.checked) {
txtBox.style.visibility = "visible";
} else {
txtBox.style.visibility = "hidden";
}
}, false);
}
function getAssociatedTextBox(ele) {
var childNodes = ele.parentNode.childNodes;
for (i = 0, j = childNodes.length; i < j; i++) {
if (childNodes[i].className == "hiddenInput") {
return childNodes[i];
}
}
}
JSFiddle

Try this,
Javascript
$(document).ready(function(){
$("input[type=checkbox]").change(function(){
var oTxt = $("#txtBox" + $(this).attr("id").replace("chkBox", ""));
if($(this).is("checked"))
oTxt.show()
else
oTxt.hide();
});
});
HTML
<input type="checkbox" id="chkBox1"/>
<input type="textbox" id="txtBox1"/>
<input type="checkbox" id="chkBox2"/>
<input type="textbox" id="txtBox2"/>

Related

Reveal additional info based on two (out of three) checkboxes JavaScript

I'm new at Javascript and I'm trying to reveal additional info only if any 2 out of 3 checkboxes are checked.
Here is my code so far (I'm trying to enter my code in the question but It's not working, sorry. I also may have made it more complicated then necessary, sorry again). I did place my code in the Demo.
<script>
var checkboxes;
window.addEvent('domready', function() {
var i, checkbox, textarea, div, textbox;
checkboxes = {};
// link the checkboxes and textarea ids here
checkboxes['checkbox_1'] = 'textarea_1';
checkboxes['checkbox_2'] = 'textarea_2';
checkboxes['checkbox_3'] = 'textarea_3';
for ( i in checkboxes ) {
checkbox = $(i);
textbox = $(checkboxes[i]);
div = $(textbox.id + '_container_div');
div.dissolve();
showHide(i);
addEventToCheckbox(checkbox);
}
function addEventToCheckbox(checkbox) {
checkbox.addEvent('click', function(event) {
showHide(event.target.id);
});
}
});
function showHide(id) {
var checkbox, textarea, div;
if(typeof id == 'undefined') {
return;
}
checkbox = $(id);
textarea = checkboxes[id];
div = $(textarea + '_container_div');
textarea = $(textarea);
if(checkbox.checked) {
div.setStyle('display', 'block');
//div.reveal();
div.setStyle('display', 'block');
textarea.disabled = false;
} else {
div.setStyle('display', 'none');
//div.dissolve();
textarea.value = '';
textarea.disabled = true;
}
}
<label for="choice-positive">
<script type="text/javascript">
function validate(f){
f = f.elements;
for (var c = 0, i = f.length - 1; i > -1; --i)
if (f[i].name && /^colors\[\d+\]$/.test(f[i].name) && f[i].checked) ++c;
return c <= 1;
};
</script>
<label>
<h4><div style="text-align: left"><font color="black">
<input type="checkbox" name="colors[2]" value="address" id="address">Full Address
<br>
<label>
<input type="checkbox" name="colors[3]" value="phone" id="phone">Phone Number <br>
<label>
<input type="checkbox" name="colors[4]" value="account" id="account">Account Number <br>
</form>
<div class="reveal-if-active">
<h2><p style = "text-decoration:underline;"><font color="green">Receive the 2 following
pieces of info:</h2></p>
</style>
Sorry i wasn't able to exactly use the code you provided but tried to change just enough to get it working.
I've uploaded a possible solution to JSFiddle - you essentially can add event listeners to the checkboxes that recheck when clicked how many are selected and show/hide via removing/adding a class e.g. additionalContactBox.classList.remove('reveal-if-active');

Apply function when any checkboxes are changed

I have an HTML form with checkboxes like so:
<form id="filterOptions" method="post" action="">
<input type="checkbox" name="filterTaxi" id="filterTaxi" />
<input type="checkbox" name="filterBicycle" id="filterBicycle" />
<input type="checkbox" name="filterCarPark" id="filterCarPark" />
<input type="checkbox" name="filterBed" id="filterBed" />
</form>
Now I want to use javascript to apply a function whenever a checkbox is changed.
At the moment I can apply a function when the first checkbox is changed like so:
document.getElementById('filterTaxi').onchange = function(){
//do something here
};
So my question is, how do I avoid writing that for every checkbox and instead have a function fired when any of the checkboxes are changed?
You can either select all input or add a class and do:
var input = document.getElementsByTagName('input');
for(var i = 0; i < input.length; i++) {
input[i].onchange = function() {
console.log(this);
}
}
onchange function can be the same for all of them.
fiddle: http://jsfiddle.net/XgS9K/
for all elements.
document.getElementById('filterOptions').onchange = function(){
alert()
};
This will give you the onchange handler for checking and unchecking of checkboxes.
var allInputs = document.getElementsByTagName('input');
for (var i = 0; i < allInputs.length; i++) {
if (allInputs[i].type == 'checkbox') {
allInputs[i].onchange = function () {
if (this.checked) {
// your checked code here
console.log('checked');
} else {
// your unchecked code here
console.log('unchecked');
}
}
}
}
DEMO http://jsfiddle.net/L324t/

document.activeElement doesn't work as expected on Chrome, what are the alternatives?

Hi,
I want to check/uncheck all the checkboxes with the same class as well as disable\enable the associated text fields when checking/unchecking a checkbox.
I managed to write a code using document.activeElement and document.getElementsByClassName that'll do exactly that, except that it doesn't work on Chrome. It's a reported bug in Chrome that it returns body instead of the actual activeElement unless the activeElement is a text field.
Is there a workaround that I can use until the bug is fixed?
My code:
JS:
function changeAll(variable) {
var current = document.activeElement;
var checkboxes = variable + "_g";
var text = variable + "_v";
var i;
if (current.checked === true) {
for (i = 0; i < document.getElementsByClassName(checkboxes).length; i++) {
document.getElementsByClassName(checkboxes)[i].checked = true;
}
for (i = 0; i < document.getElementsByClassName(text).length; i++) {
document.getElementsByClassName(text)[i].disabled = false;
}
} else {
for (i = 0; i < document.getElementsByClassName(checkboxes).length; i++) {
document.getElementsByClassName(checkboxes)[i].checked = false;
}
for (i = 0; i < document.getElementsByClassName(text).length; i++) {
document.getElementsByClassName(text)[i].disabled = true;
}
}
}
HTML:
<input type="checkbox" class="y_g" onClick="changeAll('y')">
<input type="text" class="y_v" disabled>
<input type="checkbox" class="y_g" onClick="changeAll('y')">
<input type="text" class="y_v" disabled>
<br>
<input type="checkbox" class="x_g" onClick="changeAll('x')">
<input type="text" class="x_v" disabled>
<input type="checkbox" class="x_g" onClick="changeAll('x')">
<input type="text" class="x_v" disabled>
Pass in the reference
HTML:
<input type="checkbox" class="y_g" onClick="changeAll(this,'y')">
JavaScript:
function changeAll(current, variable) {
//var current = document.activeElement;
ideally you would not be using inline events.

Checkbox to display more options

I am using ColdFusion 8 to create a search form and would like the user to be able to check a box if they want the advanced search options to appear.
Here is what I have so far:
In my javascript file:
function showDiv(advancedVal)
{
if(advancedVal == '') {
$('moreOptions').style.display = "";
} else {
$('moreOptions').style.display = "none";
}
}
In my CF file:
<input name="advanced" type="checkbox" value="" id="advanced" onclick="showDiv('');">
<div id="moreOptions" style="display:none;" class="moreOptions">
<table>
drop down boxes
</table>
</div>
The checkbox is in a different table, does this matter?
Anyone know why this isn't working?
Are you using jQuery? Then it should be:
$('moreOptions').style.display = "" should be $('#moreOptions').show()
or
$('moreOptions')[0].style.display = ""
UPD
I guess this is what you want:
function showDiv(obj) {
var more = document.getElementById('moreOptions');
more.style.display = obj.checked ? "" : "none";
}​
And change your markup:
<input name="advanced" type="checkbox" value="" id="advanced" onchange="showDiv(this)">
See demo http://jsfiddle.net/dfsq/Kexbu/2/
If you are not using jQuery, your code should be:
function showDiv(advancedVal)
{
if(advancedVal) {
document.getElementById('moreOptions').style.display = "";
} else {
document.getElementById('moreOptions').style.display = "none";
}
}
and
<input name="advanced" type="checkbox" value="" id="advanced" onchange="showDiv(this.checked)">
Here's an example: http://jsfiddle.net/XN8aK/1/
change $('moreOptions') to $('#moreOptions')

Using JavaScript to manipulate HTML input (checkbox) elements via type instead of name

I am implementing an HTML form with some checkbox input elements, and I want to have a Select All or DeSelect All button. However, I do not want to rely on the name of the input element (like this example) but rather the type because I have multiple checkbox groups with different names. Is there a way to check and uncheck all checkbox input elements within a form with JavaScript by relying on the type instead of the name?
Edit: We rely on YUI libraries, so I have access YUI if that provides a solution.
This should do it:
<script>
function checkUncheck(form, setTo) {
var c = document.getElementById(form).getElementsByTagName('input');
for (var i = 0; i < c.length; i++) {
if (c[i].type == 'checkbox') {
c[i].checked = setTo;
}
}
}
</script>
<form id='myForm'>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='button' onclick="checkUncheck('myForm', true);" value='Check'>
<input type='button' onclick="checkUncheck('myForm', false);" value='Uncheck'>
</form>
function findCheckBoxes(el, check) {
for(var i=0;el.childNodes[i];i++)
{
var child = el.childNodes[i];
if (child.type=="checkbox")
{
child.checked = check;
}
if (child.childNodes.length > 0)
this.findCheckBoxes(child, check);
}
}
iterate through the form.elements collection and check .type == "checkbox".
var button = getSelectAllButtonInFormSomeHow();
/*all formelements have a reference to the form. And the form has an elements-collection.*/
var elements = button.form.elements;
for(var i = 0; i < elements.length;i++) {
var input = elements[i];
if (input.tagName == "input" && input.type == "checkbox") input.checked = true;
}
Every input element has an attribute, type, which for checkboxes is "checkbox" so you could try something like this:
for (var i = 0; i < document.myForm.elements.length; i++) {
if (document.myForm.elements[i].type == "checkbox") {
document.myForm.elements[i].checked = true;
}
}
If jQuery is an option you can do this rather easily.
See the documentation on jQuery selectors. (The last example in the section shows how to do it with radio buttons but just replace that with check boxes.)
Is assigning a class to all required checkbox elements an option? If yes, then this is how I would do it (assuming "class_name" is the name of the css class present in all checkbox elements in question):
function selectCheckBoxes(bChecked) {
var aCheckBoxes = YAHOO.util.Dom.getElementsByClassName('class_name', 'input');
for (var i = 0; i < aCheckBoxes.length; i++) {
aCheckBoxes[i].checked = bChecked;
}
}
If you want to stay away from classes, but can get parent element by ID (or any other method, I will use ID in the example, though), than you can do this:
function selectCheckBoxes(bChecked) {
var oParent = document.getElementById('parentsID');
var aElements = oParent.getElementsByTagName('input');
for (var i = 0; i < aElements.length; i++) {
if (aElements[i].type == 'checkbox') {
aElements[i].checked = bChecked;
}
}
}
I would stick to the "class" method, however.
<html>
<head>
<script>
function selectCheckBox()
{
if(document.getElementById('id11').checked==true)
{
document.frm.id2.checked=true
document.frm.id3.checked=true
document.frm.id4.checked=true
}
if(document.getElementById('id11').checked==false)
{
document.frm.id2.checked=false
document.frm.id3.checked=false
document.frm.id4.checked=false
}
}
function selectCheckBox1()
{
if(document.getElementById('id12').checked==false)
{
document.frm.id1.checked=false
}
}
function selectCheckBox2()
{
if(document.getElementById('id13').checked==false)
{
document.frm.id1.checked=false
}
}
function selectCheckBox3()
{
if(document.getElementById('id14').checked==false)
{
document.frm.id1.checked=false
}
}
</script>
</head>
<body>
<form name="frm">
All :<input type="checkbox" id="id11" name="id1" value="1" onClick="selectCheckBox()"><br>
A. :<input type="checkbox" id="id12" name="id2" value="2" onClick="selectCheckBox1()"><br>
B. :<input type="checkbox" id="id13" name="id3" value="3" onClick="selectCheckBox2()"><br>
C. :<input type="checkbox" id="id14" name="id4" value="4" onClick="selectCheckBox3()"><br>
</form>
</body>
</html>

Categories

Resources