JavaScript Array need to display many hidden fields - javascript

Fiddle link here
<script>
function show1() {
if (document.getElementById("check1").checked == true) {
document.getElementById("info1").style.display="inline";
} else {
if (document.getElementById("check1").checked == false)
document.getElementById("info1").style.display="none";
}
}
</script>
<input type="checkbox" id="check1" name="check1" value="" onclick="show1();">
<style>
#info1, #info2 {
display: none;
}
</style>
What I need to do about 20 times is to show hidden fields info1, info2 etc. when check1, check2 is selected.

First it is always a good idea to find handlers in Javascript instead of inline events.
Second give all your inputs the same class to do so.
Have a data-* attribute that will store the corresponding input message.
You HTML would look like
HTML
<div class="container">
<div>
<input type="checkbox" id="check1" name="check1" value="" data-id="info1" class="checkbox"/>
<label for="check1">Click here for more information</label>
</div>
<div id="info1" class="info">Hidden information here will now appear onclick check1</div>
</div>
<div class="container">
<div>
<input type="checkbox" id="check2" name="check3" value="" data-id="info2" class="checkbox"/>
<label for="check2">Click here for more information</label>
</div>
<div id="info2" class="info">Hidden information here will now appear onclick check2</div>
</div>
<div class="container">
<div>
<input type="checkbox" id="check3" name="check3" value="" data-id="info3" class="checkbox"/>
<label for="check3">Click here for more information</label>
</div>
<div id="info3" class="info">Hidden information here will now appear onclick check3</div>
</div>
JS
// Get all the checkbox elements
var elems = document.getElementsByClassName('checkbox');
// iterate over and bind the event
for(var i=0; i< elems.length; i++) {
elems[i].addEventListener('change', show);
}
function show() {
// this corresponds to the element in there
// Get the info attribute id
var infoId = this.getAttribute('data-id');
if (this.checked) {
document.getElementById(infoId).style.display = "inline";
} else {
document.getElementById(infoId).style.display = "none";
}
}
Check Fiddle
This is one way of doing this.

I've updated your jsfiddle:
document.addEventListener('change', function(e) {
var id = e.target.getAttribute('data-info-id');
var checked = e.target.checked;
if (id) {
var div = document.getElementById(id);
if (div) div.style.display = checked ? 'block' : 'none';
}
});
Instead of creating an if ... else block for every checkbox, which becomes hard to maintain, I've associated every check with its DIV via the custom attribute data-info-id, which is set to the id of the aforementioned DIV.
I bind the 'change' event to the document (event delegation) and when it fires I check the source element has a data-info-id attribute. Then, I get the DIV with such id and show or hide it based on the value of the checked property.
The obvious advantage of doing it this way, via custom attributes, is that you don't depend of the position of the div, and you can change which checks shows what DIV in a declarative way, just changing the HTML.

Maybe you are looking for a javascript only solution, but there's a pretty simple solution in CSS
HTML
<div>
<input type="checkbox" id="check1" name="check1" value="" />
<label for="check1"> Click here for more information</label>
<div id="info1">Hidden information here will now appear onclick </div>
</div>
<div>
<input type="checkbox" id="check2" name="check2" value=""/>
<label for="check2"> Click here for more information</label>
<div id="info2">Hidden information here will now appear onclick </div>
</div>
CSS
input[type=checkbox] ~ div {
display: none;
}
input[type=checkbox]:checked ~ div {
display: block;
}
Fiddle here

Looks for an input with the data-enable attribute that matches to the id of the element being shown/hidden.
HTML
<input type="checkbox" data-enable="info0" name="check[]"/>
<input type="text" id="info0" name="info[]"/>
Javascript
function toggleEl(evt) {
var checkbox = evt.target;
var target = checkbox.getAttribute('data-enable');
var targetEl = document.getElementById(target);
// if checked, use backed-up type; otherwise hide
targetEl.type = (checkbox.checked)
? targetEl.getAttribute('data-type')
: 'hidden';
}
var inputs = document.getElementsByTagName('input');
for(var i=0,l=inputs.length;i<l;i++) {
var input = inputs[i];
var target = input.getAttribute('data-enable');
if(target!==null) {
var targetEl = document.getElementById(target);
// back-up type
targetEl.setAttribute('data-type',targetEl.type);
// hide it if the checkbox is not checked by default
if(!input.checked)
{ targetEl.type = 'hidden'; }
// add behavior
input.addEventListener('change',toggleEl,false);
}
}

Check out the following JSFiddle .
//<![CDATA[
// common.js
var doc = document, bod = doc.body, IE = parseFloat(navigator.appVersion.split('MSIE')[1]);
bod.className = 'js';
function gteIE(version, className){
if(IE >= version)bod.className = className;
}
function E(e){
return doc.getElementById(e);
}
//]]>
//<![CDATA[
// adjust numbers as needed
for(var i=1; i<2; i++){
(function(i){
E('check'+i).onclick = function(){
var a = E('info'+i).style.display = this.checked ? 'block' : 'none';
}
})(i);
}
//]]>

Related

How do I get the parent id in this function?

The attached code properly returns the id and the value of the checked box.
I need to get the id of the enclosing div so that I can set the display attribute to hidden.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="wrapper">
<form>
<div id="boatdiv1"><input type="checkbox" name="cb" id="boat1" value="123" onclick='doClick();'><label for='boat1'>boat1</label><br></div>
<div id="boatdiv2"><input type="checkbox" name="cb" id="boat2" value="456" onclick='doClick();' onclick='doClick();'><label for='boat2'>boat2</label><br></div>
<div id="boatdiv3"><input type="checkbox" name="cb" id="boat3" value="789" onclick='doClick();'><label for='boat3'>boat3</label><br></div>
</form>
</div>
</body>
<script>
function doClick() {
var checkedValue = null;
var inputElements = document.getElementsByName('cb');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue = inputElements[i].value;
checkedID = inputElements[i].id;
console.log('checked id = '+checkedID);
console.log('value = '+checkedValue);
break;
}
}
ParentID = checkedID.offsetParent;
console.log(ParentID.id);
}
</script>
</html>
I expected that ParentID would return the id. Instead, I get an error "TypeError: undefined is not an object (evaluating 'ParentID.id')"
You need to remove the onevent attributes and use either an onevent property or event listener instead:
<input doClick()...>
This is basically what you need to hide the parent element of clicked element (event.target):
event.target.parentElement.style.display = 'none';
Demo
Details commented in demo
// Reference the form
var form = document.forms[0];
// Register the form to the change event
form.onchange = hide;
/*
Called when a user unchecks/checks a checkbox
event.target is always the currently clicked/changed tag
Get the changed parent and set it at display: none
*/
function hide(e) {
var changed = e.target;
changed.parentElement.style.display = 'none';
console.log(`Checkbox: ${changed.id}: ${changed.value}`);
console.log(`Parent: ${changed.parentElement.id}`);
}
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="wrapper">
<form>
<div id="boatdiv1"><input type="checkbox" name="cb" id="boat1" value="123"><label for='boat1'>boat1</label><br></div>
<div id="boatdiv2"><input type="checkbox" name="cb" id="boat2" value="456"><label for='boat2'>boat2</label><br></div>
<div id="boatdiv3"><input type="checkbox" name="cb" id="boat3" value="789"><label for='boat3'>boat3</label><br></div>
</form>
</div>
</body>
</html>
Use parentNode - also note that checkedID is a string, so it doesn't have a parent. Use getElementById to get the checked input:
ParentID = document.getElementById(checkedID).parentNode;
console.log(ParentID.id);

Display Value of the Checkboxes in <p> onclick Javascript

Display the Value of the Checkbox. The message changes while the user checked or unchecked the checkbox.
I have this code but it is arranged in alphabetical manner everytime i check/uncheck a box which should not be. It should be displayed in a manner on how the user selected the checkboxes.
Javascript Code:
<script>
function callMe(x)
{
var changeableTags=document.getElementsByClassName(x.getAttribute("title"));
if(x.checked == true)
{
for(i=0; i<changeableTags.length; i++)
{
changeableTags[i].style.display="initial";
}
}
else{
for(i=0; i<changeableTags.length; i++)
{
changeableTags[i].style.display="none";
}
}
}
</script>
HTML Code:
<body>
<input type="checkbox" title="nr_1" name="abccheck" checked onChange="callMe(this)"> A <br>
<input type="checkbox" title="nr_2" name="abccheck" checked onChange="callMe(this)"> B <br>
<input type="checkbox" title="nr_3" name="abccheck" checked onChange="callMe(this)"> C <br>
<p class="nr_1" style="display:initial">A </p>
<p class="nr_2" style="display:initial">B </p>
<p class="nr_3" style="display:initial">C </p>
</body>
Hope code below help your issue.
function handleClick(cb) {
var idCheckBox = cb.getAttribute('id');
var changeableTags=document.getElementsByClassName(idCheckBox);
if(cb.checked === true){
console.log("true");
for(i=0; i<changeableTags.length; i++)
{
changeableTags[i].style.display="initial";
}
}else{
console.log("false");
for(i=0; i<changeableTags.length; i++)
{
changeableTags[i].style.display="none";
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div>
<label><input type='checkbox' checked onclick='handleClick(this);' id='1'>Checkbox 1</label>
</div>
<div>
<label><input type='checkbox' checked onclick='handleClick(this);' id='2'>Checkbox 2</label>
</div>
<div>
<label><input type='checkbox' checked onclick='handleClick(this);' id='3'>Checkbox 3</label>
</div>
<div>
<p class="1" style="display:initial">ID 1 Checked </p>
</div>
<div>
<p class="2" style="display:initial">ID 2 Checked </p>
</div>
<div>
<p class="3" style="display:initial">ID 3 Checked </p>
</div>
</body>
</html>
It is important to structure one's HTML markup with reference to the task at hand. Consider the following revision of your example code...
<input id="A" type="checkbox" title="nr_1" name="abccheck" checked> <br>
<input id="B" type="checkbox" title="nr_2" name="abccheck" checked> <br>
<input id="C" type="checkbox" title="nr_3" name="abccheck" checked> <br>
<div id="display-container">
<p id="pA">A</p>
<p id="pB">B</p>
<p id="pC">C</p>
</div>
Each input[type=checkbox] and each corresponding P element has a unique HTML id attribute assigned. The paragraphs are placed inside a container for convenience.
The ids of clicked checkbox elements can be scrutinised by JavaScript in the following way...
First, add an event listener to each target element...
/* collect all checkboxes */
var cBoxes = document.querySelectorAll(
"input[name=abccheck]"
};
/* loop and add an event listener
to each element in the collection */
[].slice.call(cBoxes).forEach(function(cb) {
cb.addEventListener(
"click", clickMe, false
);
});
The clickMe() function will be called whenever an input with name=abccheck is clicked. Why add and event listeners here?
To find out which element has been clicked you can poll the event's .target in the clickMe() function...
function clickMe(event) {
var boxID = event.target.id;
// i.e. boxID = A, B or C
}
Now, rather than showing or hiding HTML P elements the boxID variable can be used to find, insert or remove the corresponding P into the div#display-container element, like so...
function clickMe(event) {
var boxID = event.target.id;
var container = document.getElementById(
"display-container"
);
/* look for a corresponding P-element */
var pCheck = document.getElementById(
"p" + boxID
);
/* variable to hold newly created P-element */
var pTag;
/* if the corresponding P-element
exists then remove it, otherwise
create and add it */
if (pCheck) {
/* remove */
container.removeChild(pCheck);
} else {
/* create new P-element */
pTag = document.createElement("p");
/* add unique id to new P */
pTag.id = "p" + boxID;
/* add text to new P */
pTag.textContent = boxID;
/* insert into #display-container */
container.appendChild(pTag);
}
}
Each time a checkbox is clicked the corresponding paragraph will be removed/added from div#display-container - in the order the events occurred.
JSFIDDLE here.
See MDN for more info about...
Document.querySelectorAll()
Element.addEventListener()
Event.target
Node.removeChild()
Node.appendChild()
Document.createElement()
[].slice.call()

Show/Hide Form Fields on checkbox checked/unchecked

I'm using JavaScript to show/hide additional fields in my form depending on whether the relevant checkbox is clicked. The fields are hidden and they do show when the checkbox is ticked, but DO NOT hide when it is un-ticked. However, the fields do hide when I tick the checkbox again.
I have the checkbox with id='cb_post' and an onclick command to fetch showDiv() from my external javascript file. I also have the hidden field with id='hiddenDiv'.
My javascript script is simple:
function showDiv() {
if (document.getElementById('hiddenDiv').style.display == 'block') {
(document.getElementById('hiddenDiv').style.display = 'none');
} else {
document.getElementById('hiddenDiv').style.display = 'block';
}
}
Can anyone advise on how to hide the fields when the checkbox is unticked?
You should think about using jQuery
$("#hiddenDiv").hide();
$("#hiddenDiv").show();
and something nicer
$("#hiddenDiv").fadeOut();
$("#hiddenDiv").fadeIn();
I think using jQuery toggle would fit better for your problem:
<input type="checkbox" id="cb_post">
<div id = "hiddenDiv">
<li>Toggle me</li>
</div>
$("#cb_post").on('click', function(){
$("#hiddenDiv").toggle();
});
Maybe using the event onchange instead of onclick would be more elegant.
https://jsfiddle.net/qqL0sxxs/
Here is working code :
var chebx = document.getElementsByClassName('toggleField');
for (var i = 0; i < chebx.length; i++) {
chebx[i].addEventListener('click', toggleField, false);
}
function toggleField() {
var field = document.getElementById(this.dataset.target);
if (field) {
switch (this.checked) {
case true:
if (field.classList.contains('hide')) {
field.classList.remove('hide');
} else {
field.classList.add('hide');
}
break;
default:
break;
}
}
}
.hide {
display: none;
}
<lable for='toggleField'>Toggle Field</lable>
<input type="checkbox" data-target='field1' class='toggleField'>
<input type='text' class='hide' id='field1' />
<hr>
<lable for='toggleField'>Toggle Field</lable>
<input type="checkbox" data-target='field2' class='toggleField'>
<input type='text' class='hide' id='field2' />

jquery - show textbox when checkbox checked

I have this form
<form action="">
<div id="opwp_woo_tickets">
<input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][0][enable]">
<div class="max_tickets">
<input type="text" name="opwp_wootickets[tickets][0][maxtickets]">
</div>
<input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][1][enable]">
<div class="max_tickets">
<input type="text" name="opwp_wootickets[tickets][1][maxtickets]">
</div>
<input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][2][enable]">
<div class="max_tickets">
<input type="text" name="opwp_wootickets[tickets][2][maxtickets]">
</div>
</div>
</form>
As of now, I'm using this jquery code to show textbox when checkbox checked.
jQuery(document).ready(function($) {
$('input.maxtickets_enable_cb').change(function(){
if ($(this).is(':checked')) $('div.max_tickets').show();
else $('div.max_tickets').hide();
}).change();
});
It works fine, but it shows all textboxes when checked.
Can someone help me to fix it?
Here is the demo of my problem.
http://codepen.io/mistergiri/pen/spBhD
As your dividers are placed next to your checkboxes, you simply need to use jQuery's next() method to select the correct elements:
if ($(this).is(':checked'))
$(this).next('div.max_tickets').show();
else
$(this).next('div.max_tickets').hide();
Updated Codepen demo.
From the documentation (linked above), the next() method selects:
...the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
Here we're selecting the next div.max_tickets element. However in your case just using next() with no parameters would suffice.
Assuming markup will stay in same order can use next()
jQuery(document).ready(function($) {
$('input.maxtickets_enable_cb').change(function(){
$(this).next()[ this.checked ? 'show' : 'hide']();
}).change();
});
Change:
if ($(this).is(':checked')) $('div.max_tickets').show();
To:
if ($(this).is(':checked')) $(this).next('div.max_tickets').show();
jsFiddle example here
Maybe try selecting the next element only?
change:
if ($(this).is(':checked')) $('div.max_tickets').show();
to:
if ($(this).is(':checked')) $(this).next('div.max_tickets').show();
Put a div across your checkbox and text box
<form action="">
<div id="opwp_woo_tickets">
<div>
<input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][0][enable]">
<div class="max_tickets">
<input type="text" name="opwp_wootickets[tickets][0][maxtickets]">
</div>
</div>
<div>
<input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][1][enable]">
<div class="max_tickets">
<input type="text" name="opwp_wootickets[tickets][1][maxtickets]">
</div>
</div>
<div>
<input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][2][enable]">
<div class="max_tickets">
<input type="text" name="opwp_wootickets[tickets][2][maxtickets]">
</div>
</div>
</div>
</form>
and replace your jquery code with this one below,
jQuery(document).ready(function($) {
$('input.maxtickets_enable_cb').change(function(){
if ($(this).is(':checked')) $(this).parent().children('div.max_tickets').show();
else $(this).parent().children('div.max_tickets').hide();
}).change();
});
I have tested it and it works.
While you may need a JavaScript solution for other reasons, it's worth noting that this can be achieved with pure CSS:
input + div.max_tickets {
display: none;
}
input:checked + div.max_tickets {
display: block;
}
JS Fiddle demo.
Or, with jQuery, the simplest approach seems to be:
// binds the change event-handler to all inputs of type="checkbox"
$('input[type="checkbox"]').change(function(){
/* finds the next element with the class 'max_tickets',
shows the div if the checkbox is checked,
hides it if the checkbox is not checked:
*/
$(this).next('.max_tickets').toggle(this.checked);
// triggers the change-event on page-load, to show/hide as appropriate:
}).change();
JS Fiddle demo.
Reference:
CSS:
:checked pseudo-class.
jQuery:
change().
next().
toggle().
protected void EnableTextBox()
{
int count = int.Parse(GridView1.Rows.Count.ToString());
for (int i = 0; i < count; i++)
{
CheckBox cb = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1");
CheckBox cb1 = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox2");
CheckBox cb2 = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox3");
TextBox tb = (TextBox)GridView1.Rows[i].Cells[4].FindControl("txtration");
TextBox tb1 = (TextBox)GridView1.Rows[i].Cells[5].FindControl("txtjob");
TextBox tb2 = (TextBox)GridView1.Rows[i].Cells[6].FindControl("txtaadhar");
if (cb.Checked == true)
{
tb.Visible = true;
}
else
{
tb.Visible = false;
}
if (cb1.Checked == true)
{
tb1.Visible = true;
}
else
{
tb1.Visible = false;
}
if (cb2.Checked == true)
{
tb2.Visible = true;
}
else
{
tb2.Visible = false;
}
}
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
EnableTextBox();
}

Input field hidden dynamically can not be shown later

I have a form with a text input and a radio button pair used to select yes/no. For purposes of keeping this simple, the radio button click event checks the value and if yes, it shows the input text field. If no, it hides the input field. I also check the initial state on document ready and show/hide the input text field.
I find that clicking No results in the input hiding using a jQuery .hide() method. But when I select Yes the resulting .show() method call does not show the input. If I set the radio to Yes and then refresh the page then the input shows up just fine.
Firebug show no input tag. It's like clicking No radio deleted the input from the DOM.
Here's the JS code sample:
$(document).ready(function() {
if ($('#cost_sharing_yes').attr('checked') == 'checked') {
$('input#Institutional_CS_TP').show();
} else {
$('input#Institutional_CS_TP').hide();
}
$('#cost_sharing_yes').click(function() {
$('input[id="Institutional_CS_TP"]').show();
});
$('#cost_sharing_no').click(function() {
$('input#Institutional_CS_TP').fadeOut("fast");
});
}
You are missing ) for closing ready function:
$(document).ready(function() {
} // <--
For getting the checked property of the inputs perperly you should use prop method instead of attr.
$(document).ready(function() {
var isChecked = $('#cost_sharing_yes').prop('checked');
$('#Institutional_CS_TP').toggle(isChecked);
// ..
})
I figured out my problem. It was a self-inflicted coding problem.
To keep the example simple I had removed another function call in the mix that I didn't think had any bearing on the problem. I was wrong. In that function I had
$('td#Institutional_CS_TP).text('$0');
$('input[name="Institutional_CS_TP"]').val('0.00');
This resulted in only the td value showing, not the input inside that same td.
Both my td and the input tags inside the td had the same ID values...not a good idea.
html code
<div id="myRadioGroup">
Value Based<input type="radio" name="cars" value="2" />
Percent Based<input type="radio" name="cars" value="3" />
<br>
<div id="Cars2" class="desc" style="display: none;">
<br>
<label for="txtPassportNumber">Commission Value</label>
<input type="text" id="txtPassportNumber" class="form-control" name="commision_value" />
</div>
<div id="Cars3" class="desc" style="display: none;">
<br>
<label for="txtPassportNumber">Commission Percent</label>
<input type="text" id="txtPassportNumber" class="form-control" name="commision_percent" />
</div>
</div>
Jquery code
function myFunction() {
var x = document.getElementById("myInput");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
function myFunction1() {
var y = document.getElementById("myInput1");
if (y.type === "password") {
y.type = "text";
} else {
y.type = "password";
}
}

Categories

Resources