How do I get the parent id in this function? - javascript

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);

Related

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()

Is it possible to set A javascript variable value to an elements id name using an onclick event

Hey this is my first time posting here I was wondering it it is possible to set a javascripts variable Value to an html elements id name when clicking on said html element
Example
<div id="01" onclick="Myfunction()"></div>
MyFunction(){
variable x = 01(Divs Id number)
}
Use this.id and pass this(current element) as argument
function Myfunction(elem) {
var x = elem.id; //Or this.getAttribute('id')
console.log(x)
}
<div id="01" onclick="Myfunction(this)">Click me</div>
Yes it's possible ... below is demo on this ..
<!DOCTYPE html>
<html>
<body>
<script>
function Myfunction(ctrl){
var id= ctrl.id;
var name= ctrl.name;
console.log(id);
console.log(name);
alert(id);
alert(name);
}
</script>
<div id="01" name='divOne' onclick="Myfunction(this)">div sample</div>
<input id="02" type="number" name='txtOne' onclick="Myfunction(this)"></p>
</body>
</html>
Remember only input types html controls can have name property.. that's why div will return undefined on name ..

JavaScript Array need to display many hidden fields

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);
}
//]]>

Referencing and changing attributes of HTML button inside container

Below is the HTML code I am playing with. All it does is create an element with two buttons: "Element1" (TitleButton) and "Add". By clicking on "Add" the element is cloned and assigned id="element 2". What I am not able to do is assign value "Element2" for the TitleButton of the cloned element. How can I do it, preferably inside addNode() function? If it is not possible then what are other ways? Thanks
<HTML>
<HEAD>
<TITLE>Dynamically add Textbox, Radio, Button in html Form using JavaScript</TITLE>
<SCRIPT language="javascript">
function addNode(element) {
var adding_element = element.parentNode;
var added_element=adding_element.cloneNode(true);
added_element.setAttribute("id","element 2");
var cont = adding_element.parentNode;
cont.appendChild(added_element);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<div name="container" id="container">
<div name="element 1" id="element 1">
<input type="button" value= "element1"; name="TitleButton" />
<input type="button" value="Add" name="add[]" onclick="addNode(this)" />
</div>
</div>
</FORM>
</BODY>
</HTML>
You can use firstElementChild property.
var id = 2;
function addNode(element) {
var adding_element = element.parentNode;
var added_element = adding_element.cloneNode(true);
added_element.setAttribute("id", "element" + id);
added_element.firstElementChild.setAttribute('value', 'element ' + id);
var cont = adding_element.parentNode;
cont.appendChild(added_element);
id++;
}
http://jsfiddle.net/SUkYg/1/

How to get all elements which name starts with some string?

I have an HTML page. I would like to extract all elements whose name starts with "q1_".
How can I achieve this in JavaScript?
A quick and easy way is to use jQuery and do this:
var $eles = $(":input[name^='q1_']").css("color","yellow");
That will grab all elements whose name attribute starts with 'q1_'. To convert the resulting collection of jQuery objects to a DOM collection, do this:
var DOMeles = $eles.get();
see http://api.jquery.com/attribute-starts-with-selector/
In pure DOM, you could use getElementsByTagName to grab all input elements, and loop through the resulting array. Elements with name starting with 'q1_' get pushed to another array:
var eles = [];
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.indexOf('q1_') == 0) {
eles.push(inputs[i]);
}
}
HTML DOM querySelectorAll() method seems apt here.
W3School Link given here
Syntax (As given in W3School)
document.querySelectorAll(CSS selectors)
So the answer.
document.querySelectorAll("[name^=q1_]")
Fiddle
Edit:
Considering FLX's suggestion adding link to MDN here
You can use getElementsByName("input") to get a collection of all the inputs on the page. Then loop through the collection, checking the name on the way. Something like this:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<input name="q1_a" type="text" value="1A"/>
<input name="q1_b" type="text" value="1B"/>
<input name="q1_c" type="text" value="1C"/>
<input name="q2_d" type="text" value="2D"/>
<script type="text/javascript">
var inputs = document.getElementsByTagName("input");
for (x = 0 ; x < inputs.length ; x++){
myname = inputs[x].getAttribute("name");
if(myname.indexOf("q1_")==0){
alert(myname);
// do more stuff here
}
}
</script>
</body>
</html>
Demo
Using pure java-script, here is a working code example
<input type="checkbox" name="fruit1" checked/>
<input type="checkbox" name="fruit2" checked />
<input type="checkbox" name="fruit3" checked />
<input type="checkbox" name="other1" checked />
<input type="checkbox" name="other2" checked />
<br>
<input type="button" name="check" value="count checked checkboxes name starts with fruit*" onClick="checkboxes();" />
<script>
function checkboxes()
{
var inputElems = document.getElementsByTagName("input"),
count = 0;
for (var i=0; i<inputElems.length; i++) {
if (inputElems[i].type == "checkbox" && inputElems[i].checked == true &&
inputElems[i].name.indexOf('fruit') == 0)
{
count++;
}
}
alert(count);
}
</script>
You can try using jQuery with the Attribute Contains Prefix Selector.
$('[id|=q1_]')
Haven't tested it though.

Categories

Resources