Show / hide several div - javascript

I use this script :
<script language="javascript">
function toggle() {
var ele = document.getElementById("mydiv");
var text = document.getElementById("displayText");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "show";
}
else {
ele.style.display = "block";
text.innerHTML = "hide";
}
}
</script>
Called by :
echo '<a id="displayText" href="javascript:toggle();">show</a>';
i want to show / hide several div (not in a list or a form)
i try :
var ele = document.getElementById("mydiv", "mydiv2");
but it's showing and hidding only the first div

Description
This is not jQuery. You should use the jQuery functions to guarantee cross browser compatibilty.
Check out my sample and this jsFiddle
Sample
<div id="mydiv">test</div>
<div id="displayText">test2</div>
$(function() {
$("#displayText").click(function() {
$("#mydiv").toggle();
});
});
More Information
jsFiddle
jQuery.toggle()
jQuery.click()

The getElementById() function accepts a single argument, so you cannot pass it a list of ids. There are a number of options, I suggest two of them:
Use an array of divs and iterate through it, e.g.
var divs = [ 'mydiv1', 'mydiv2', ... ];
for ( var i = 0; i < divs.length; i++ ) {
var div = document.getElementById( divs[ i ] );
...
}
Use a library such as jQuery that lets you operate on lists of items easily. In that case you could mark all your divs with an appropriate class, e.g. myclass, and use something like:
$(".myclass").hide()

If you can use include jQuery in your page then use jQuery instead of pure javascript to make your life simpler. Try this
function toggle() {
var ele = $("#mydiv");
var text = $("#displayText");
if(ele.is(':visible')) {
ele.hide();
text.html("show");
}
else {
ele.show();
text.html("hide");
}
}
If you want to select multiple element in jQuyer then you can pass multiple selectors seperated by a comma.
var elems = $("#mydiv, #mydiv1, #mydiv2");
elems.show();//Will show all the selected elements
elems.hide();//Will hide all the selected elements

If you want to do it in plain javascript, you could try something like this:
<script type="text/javascript">
var elements = [ 'mydiv', 'mydiv2' ]
foreach ( elem in elements )
{
var e = document.getElementById(elem);
// show/hide here
}
</script>

Related

JavaScript/CSS Show respective div on click from grid

I have a working grid that show a cell for every title in the json:
async function loop_iteration(json, i, arr) {
arr.push(`<a onClick="show()" class="cell" id=${i}"><div >${json[i].title}</div> </a>`)
arr.push(`<div class="info" id=${i}>${json[i].title}<br><br><br><br><br>Game Size: ${json[i].size}<br><br>Last Update: ${json[i].date}</div>`)
}
I want to show on click of the class info.
The problem is that it gives always the same title(first), it's like is always the first cell to be clicked
I show the info div like this:
<script>
function showinfo() {
var node = document.querySelector('.cell.info')
var visibility = node.style.visibility;
node.style.visibility = visibility == "visible" ? 'hidden' : "visible"
}
</script>
while if i show the div using this:
function show(){
var divsToHide = document.getElementsByClassName("info");
for(var i = 0; i < divsToHide.length; i++)
{
divsToHide[i].style.visibility="visible";
}
//document.getElementsByClassName('info')['${i}'].style.visibility = 'visible';
}
happen something strange, the div showed is not the first but is like it show all the div
Thanks for any help.
I find out the problem.
It was the javascript, so i extract the id and then iterate the class with the id
function show(clicked_id){
clicked_id = parseFloat(clicked_id);
document.getElementsByClassName('info')[clicked_id].style.visibility = 'visible';
}

How to hide item in html with jquery using variable

i'm trying to use this simple script to hide some element by ID, i have the id in a variable but it doesn't work..
this is the code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script>
function filter(id_get) {
$(".product").each(function(index) {
var f = this.id;
if (!f.includes(id_get)) {
var hash = "#";
var cmp = hash.concat(f);
$(cmp).attr("display", "none");
}
});
}
</script>
if i do a console.log(cmp) it displays correct product id to remove, but it doesn't hide the div.
i've also tried $(cmp).hide
You are attempting to change an attribute directly. display is not an attribute. style is an attribute. You can change the display property of the style attribute. Change $(cmp).attr("display","none"); to:
$(cmp).css("display", "none");
Or, you can just use the built in jQuery hide function. Change $(cmp).attr("display","none"); to:
$(cmp).hide();
In context:
function filter(id_get){
$( ".product" ).each(function( index ) {
var f = this.id;
if(!f.includes(id_get)){
var hash = "#";
var cmp = hash.concat(f);
$(cmp).hide();
}
});
}

javascript to hide a div if empty

I am looking for javascript (not jquery as client has specified) to hide a div with class=top, if the div has no content. I can do it using jquery like below, but need to use javascript. Any ideas please?
$('div.top:empty').hide();
Something like:
var top = document.getElementsByClassName("top");
for (var i = 0; i < top.length; i++) {
if (top[i].innerHTML.length == 0)
top[i].style.display = "none";
}
you could use innerHTML property to check if the selected div.top element contains content. something like this.
var topDiv = document.getElementsByClassName('top')[0];
if(topDiv.innerHTML === '') {
topDiv.style.display = 'none';
}
(if(document.getElementById("yourDiv").innerHTML=="")
{
document.getElementById("yourDiv").style.display='none';
}
You need to give id to DIV which you want to hide As there are no function in javascript by which you can find div by class.
HTML:
<div class="top" id="divId"></div>
Javascript:
if( document.getElementById("divId").innerHTML == "" )
{
document.getElementById("divId").style.display='none';
}
Use the following script:
var divContent = $('div .top')[0].innerHTML;
if (divContent === '')
{
$('div .top').hide();
}

javascript unobtrusive

i have an html page, which is consist of many hyperlink like this inside body tag...
User Name
then i decide to use unobtrusive javascript ... then i'd like to change all the "a" tag to be...
<a id="354313" href=#>User Name</a>
when i click the second link above, i want that it'll call a function like the first link does,...
my question is how to get all the "a" element inside body tag then apply a function depend it's id...
With jQuery, something like this:
$('a').click(function() {
var id = this.getAttribute('id');
// Do something...
});
If you want it to work on all elements ever created, use this:
$('a').live('click', function() {
var id = this.getAttribute('id');
// Do something...
});
I hope this is what you are trying.
<script type='text/javascript'>
var alA = document.getElementsByTagName("a");
for(var aCounter=0;aCounter<alA.length;aCounter++) {
var singleA = alA[aCounter];
singleA.onclick = function () {
window.open = "http://www.example.com/?id="+singleA.id;
}
}
<script>
What you're after is this code:
<script type="text/javascript">
window.onload = function WindowLoad() {
var arrLinks = document.getElementsByTagName("a");
for (var i = 0; i < arrLinks.length; i++) {
var oLink = arrLinks[i];
var sCurHref = oLink.href;
if (sCurHref.indexOf("?id=") >= 0) {
var ID = sCurHref.split("?id=")[1];
if (ID.length > 0) {
oLink.id = ID;
oLink.href = "#";
oLink.onclick = function() {
document.location.href = sCurHref;
return false;
}
}
}
}
}
</script>
This will iterate all the links, changing the visible HREF to "#" and preserving their functionality, applying the proper ID. (Though you didn't say what's the use of that ID)
Feel free to mess around with the live test case: http://jsfiddle.net/yahavbr/uMbEY/
Something like:
<script language="javascript">
function myFunction(id)
{
alert(id);
}
</script>
<a id="354313" onclick="myFunction(this.id);" href="#">;User Name<;/a>
Not sure though Test it :)
I will rather say that add class to the links u want to handle this way
<a class="mylink" ... >User Name </a>
Now read the elements by class name. If you are using new browsers or any JS library like JQuery its great.
var links = document.getElementsByClassName("mylink") //Method in Mozilla Browser
Above are the links that you can process nicely without getting into trouble.
// Function that you want to call
function fake(id)
{
// Your content
}
// Get all "a" elements and put it in an Array
var links = window.document.getElementsByTagName("a");
for (var i=0; i<links.length; ++i)
{
fake(links[i].id);
}

How to get all elements inside "div" that starts with a known text

I have a div element in an HTML document.
I would like to extract all elements inside this div with id attributes starting with a known string (e.g. "q17_").
How can I achieve this using JavaScript ?
If needed, for simplicity, I can assume that all elements inside the div are of type input or select.
var matches = [];
var searchEles = document.getElementById("myDiv").children;
for(var i = 0; i < searchEles.length; i++) {
if(searchEles[i].tagName == 'SELECT' || searchEles.tagName == 'INPUT') {
if(searchEles[i].id.indexOf('q1_') == 0) {
matches.push(searchEles[i]);
}
}
}
Once again, I strongly suggest jQuery for such tasks:
$("#myDiv :input").hide(); // :input matches all input elements, including selects
Option 1: Likely fastest (but not supported by some browsers if used on Document or SVGElement) :
var elements = document.getElementById('parentContainer').children;
Option 2: Likely slowest :
var elements = document.getElementById('parentContainer').getElementsByTagName('*');
Option 3: Requires change to code (wrap a form instead of a div around it) :
// Since what you're doing looks like it should be in a form...
var elements = document.forms['parentContainer'].elements;
var matches = [];
for (var i = 0; i < elements.length; i++)
if (elements[i].value.indexOf('q17_') == 0)
matches.push(elements[i]);
With modern browsers, this is easy without jQuery:
document.getElementById('yourParentDiv').querySelectorAll('[id^="q17_"]');
The querySelectorAll takes a selector (as per CSS selectors) and uses it to search children of the 'yourParentDiv' element recursively. The selector uses ^= which means "starts with".
Note that all browsers released since June 2009 support this.
Presuming every new branch in your tree is a div, I have implemented this solution with 2 functions:
function fillArray(vector1,vector2){
for (var i = 0; i < vector1.length; i++){
if (vector1[i].id.indexOf('q17_') == 0)
vector2.push(vector1[i]);
if(vector1[i].tagName == 'DIV')
fillArray (document.getElementById(vector1[i].id).children,vector2);
}
}
function selectAllElementsInsideDiv(divId){
var matches = new Array();
var searchEles = document.getElementById(divId).children;
fillArray(searchEles,matches);
return matches;
}
Now presuming your div's id is 'myDiv', all you have to do is create an array element and set its value to the function's return:
var ElementsInsideMyDiv = new Array();
ElementsInsideMyDiv = selectAllElementsInsideDiv('myDiv')
I have tested it and it worked for me. I hope it helps you.
var $list = $('#divname input[id^="q17_"]'); // get all input controls with id q17_
// once you have $list you can do whatever you want
var ControlCnt = $list.length;
// Now loop through list of controls
$list.each( function() {
var id = $(this).prop("id"); // get id
var cbx = '';
if ($(this).is(':checkbox') || $(this).is(':radio')) {
// Need to see if this control is checked
}
else {
// Nope, not a checked control - so do something else
}
});
i have tested a sample and i would like to share this sample and i am sure it's quite help full.
I have done all thing in body, first creating an structure there on click of button you will call a
function selectallelement(); on mouse click which will pass the id of that div about which you want to know the childrens.
I have given alerts here on different level so u can test where r u now in the coding .
<body>
<h1>javascript to count the number of children of given child</h1>
<div id="count">
<span>a</span>
<span>s</span>
<span>d</span>
<span>ff</span>
<div>fsds</div>
<p>fffff</p>
</div>
<button type="button" onclick="selectallelement('count')">click</button>
<p>total element no.</p>
<p id="sho">here</p>
<script>
function selectallelement(divid)
{
alert(divid);
var ele = document.getElementById(divid).children;
var match = new Array();
var i = fillArray(ele,match);
alert(i);
document.getElementById('sho').innerHTML = i;
}
function fillArray(e1,a1)
{
alert("we are here");
for(var i =0;i<e1.length;i++)
{
if(e1[i].id.indexOf('count') == 0)
a1.push(e1[i]);
}
return i;
}
</script>
</body>
USE THIS I AM SURE U WILL GET YOUR ANSWER ...THANKS

Categories