show/hide html content in javascript - javascript

I have response which is coming from backend . Now i want to create some links, if i click those links it should display html content below that link and if i click that link again those html content should go. I know jquery hide() and show() . But here i am using for loop and i am not able to find DOM element ,
as follows,
var html = "<div id=finalDiv></div>";
$("#finalDiv").dialog();
var ht;
for(var i in response) {
ht +="<table><tr><td><label>A:</label></td><td><a onclick=\"showOneLink('"+response[i].B+"','"+i+"')\" >'"+response[i].A+"'</a></td></tr>";
ht += "<tr><td><div id=show'"+i+"'Link style='dislay:none;'></div></td></tr></table>";
}
$("#finalDiv").append(ht);
Now when i click showOneLink , hidden div should display but that div's DOM will not be created . As ,
function showOneLink(B,i) {
var htm = "<b>log:'"+B+"'</b>";
$("#show"+i+"Link").css('display','block');
$("#show"+i+"Link").append(htm);
}

The problem is this id attribute:
id=show'"+i+"'Link
That will produce invalid HTML: id=show'5'Link
Change it to:
ht += "<tr><td><div id='show"+i+"Link' style='dislay:none;'></div></td></tr></table>";
Also use toggle() instead of css():
$("#show"+i+"Link").toggle();

Selectors are Strings, close the ""
like $("#show"+i+"Link");
or the hole code:
function showOneLink(B,i) {
var htm = "<b>log:'"+B+"'</b>";
$("#show"+i+"Link").css('display','block');
$("#show"+i+"Link").append(ht);
}
and better use toggle:
$("#show"+i+"Link").append(ht);
$("#show"+i+"Link").toggle();

Related

Create div scrollable elements according to the number of elements in an String array

I'm quiet new above all on Javascript technology. I want to create various div according to the number of string into an array of checked checkboxes but after my code it only displays one div every time... I must go through a jquery dialog to display it !
My JSP
<div style="overflow: scroll;" id="listCurrentContact"></div>
My listContact.js
varPopup = $('#dialogMultiplesDeleteConfirmation').dialog({
resizable : false,
modal : true,
autoOpen : false,
width : 500,
open: function(){
var SuppressCheckboxItems = [];
// I put into an array the different value of checked checkboxes
$("input:checkbox[id=suppressCheckbox]:checked").each(function() {
SuppressCheckboxItems.push($(this).val());
});
var z = document.createElement('div');
// I suppress the ',' between each element
var test = SuppressCheckboxItems.toString();
var tab = test.split(",");
for(var i = 0; i < tab.length; i++){
z.innerHTML = tab[i];
$('#listCurrentContact').html(z);
}
Have you tried using .append instead of .html while concatenating your checkboxes to #listCurrentContact.
You can refer this document: https://www.w3schools.com/jquery/html_html.asp to see that .html() replaces the previous content with the new content whereas what you are trying to achieve here is appending the entire array of values to the div. Look at how .append() works in this link : https://www.javascripttutorial.net/javascript-dom/javascript-append/. Just to give you a brief overview, when you write a .append() on any element, it doesnot replace the previous content with the new content but instead attaches/concatenates the new content after the previous content.
You should use $('#listCurrentContact').append(z);
Thanks to SaloniMishra Ive found the good answer. It just needed to change the .html() to .append() but with that if the customer just quit the jquery dialog and retry the previous elements stayed in the div so you need to clean every elements before to relaunch the function with the function removeChild()! Thanks all !
open : function() {
var SuppressCheckboxItems = [];
const currentDiv = document.getElementById('listCurrentContact');
while (currentDiv.firstChild) {
currentDiv.removeChild(currentDiv.lastChild);
}
$("input:checkbox[id=suppressCheckbox]:checked").each(function() {
var z = document.createElement('div');
z.innerHTML = $(this).attr("name");
$("#listCurrentContact").append(z);
});

How to get text of element in a variable using jquery?

var markup = '<div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">Employee Self-Service pages have been corrected but may require you to refresh the page.</div><div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC"> </div><div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">If the problem remains, follow these instructions.  </div>';
var str = "";
$(markup).find("div[class^='ExternalClass']").each(function(){
str += $(this).text();
})
How do I grab content of all the divs in the markup that starts with ExternalClass?
$(markup) selector contain all ExternalClass class and you can't use .find() because it doen't any matched child. You need to use .filter() to filter selected element.
var markup = "<div...";
var str = "";
$(markup).filter("div[class^='ExternalClass']").each(function(){
str += $(this).text();
})
var markup = '<div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">Employee Self-Service pages have been corrected but may require you to refresh the page.</div><div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC"> </div><div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">If the problem remains, follow these instructions.  </div>';
$(markup).filter("div[class^='ExternalClass']").each(function(){
console.log($(this).text());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
jQuerys .find() only loops through the children of the specific HTML you selected. Your variable markup has no children with the fitting class selector.
The easiest way I can imagine getting this solved, is to wrap all you have in markup inside another div, and then use your jQuery selector - that works:
var markup = '<div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">Employee Self-Service pages have been corrected but may require you to refresh the page.</div><div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC"> </div><div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">If the problem remains, follow these instructions.  </div>';
markup = '<div>' + markup + '</div>';
var str = "";
$(markup).find("div[class^='ExternalClass']").each(function(){
str += $(this).text();
})

Append data from div to link url

I am trying to have a div element on every page of my site that will contain the product number and then have a link that will put that number at the end.
For example,
<div id="productnumber">01101</div>
https://example.com/#
Then put the contents of the element with id "productnumber" after the # of the link.
Any idea if this is possible? Since this would make life easier than editing all existing pages and their respective php files.
Check for Element.innerHTML. You could use some inline JS and append it to the href-Attribute (which should be were id="purchaseurl" is now)
You can add a simple script to all your pages.
document.addEventListener("DOMContentLoaded", function() {
var productNumber = document.getElementById('productnumber').textContent;
Array.prototype.forEach.call(document.querySelectorAll('a[href~="purchaseurl"]'), function(link) {
// if you want to change the link
var currentHref = link.getAttribute('href');
link.setAttribute('href', currentHref + '#' + productNumber);
// if you want to change anchor text
var currentText = link.innerHTML;
link.innerHTML = currentText + productNumber;
});
});
<div id="productnumber">01101</div>
https://example.com/#
See getElementById, getElementsByTagName, and nextSibling.
var data = document.getElementById('productnumber'),
url = data.nextSibling.nextSibling;
url.innerText += data.innerText;
<div id="productnumber">01101</div>
https://example.com/#

jquery .html() VS innerHTML()

People on here are recommending that I use jQuery, but when I changed the code to jQuery and used .html() it is like it did nothing. I even removed half of the html code that needed to be added as someone suggested I was asking way to much of innerHTML and HTML.
In Simple task, all I want is for when a user click on the DIV that it runs the onClick event.
html += "<div onClick='loadnewsstory();' class='news'> this is a test story, for this test story we are not getting data from JSON</div>";
I have tried both
$("#activecontent").html(html);
document.getElementById("activecontent").innerHTML
The problem I have is relating to the following code.
function newsstories()
{
document.getElementById("activecontent").innerHTML = "<h1 class='newsheader'>Latest News</h1>";
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","http://test.com/?uri=loadnews",false);
xmlhttp.send();
var newsreponse = JSON.parse(xmlhttp.responseText);
for (var i = 0, len = newsreponse.length; i < len; ++i) {
var news = newsreponse[i];
if(i % 2 == 0){
cssclass = "even";
}
else
{
cssclass = "odd";
}
// alert(news.featured_image);
document.getElementById("activecontent").innerHTML = document.getElementById("activecontent").innerHTML + "<div class='news " + cssclass + "'><div class='newstitle'><div class='newstitlecolor' id='news_"+ countstory+"'><a href='javascript:loadnewsstory();'>" + news.post_title + "</a></div></div><div class='base' style='background: url('" + news.featured_image + "');'><img src='" + news.featured_image + "' style='width:100%; height:100%;'/></div></div>";
}
}
you will see in this area i have a link
<a href='javascript:loadnewsstory();'>" + news.post_title + "</a>
it suppose to fire
function loadnewsstory()
{
navigator.notification.alert(device.uuid);
}
but I am not getting that fire.
Yes this is a web app for iOS and Cordova but I believe this is a javascript issue.
Don't use +=, as it is used in an improper instance and returns an "unexpected token" error because var html was not previously equal to anything. I removed it and it appeared to fix the problem. Fiddle
If you must use += set var html = $("#activecontent").html(), then you may afterwards use += when you re-define the variable (Fiddle 2)
If your structure looks like
html
<div id="activecontent">
<div class='news'>Story 1</div>
<div class='news'>Story 2</div>
</div>
and you want each div.news to by dynamic and clickable, you could do that like this with jQuery
javascript
$(function(){
$("#activecontent").on('click', '.news', function(){
//You clicked the div
console.log( 'Clicked', $(this) );
});
});
And if you want to append divs to your #activecontent with an ajax request. Let's assume your JSON looks like
json
[
{ "id": 1, "content": "My first story" },
{ "id": 2, "content": "Another one" },
{ "id": 3, "content": "Last story" }
]
Your javascript to load that could look like
javascript
$.getJSON( "http://url_of_json.json", function(result){
for(var i in result){
$("#activecontent").append( $("<div>").addClass('news').html(result[i].content) );
}
});
alternative javascript for the ajax which is faster on the DOM
$.getJSON( "http://url_of_json.json", function(result){
var newHtml = "";
for(var i in result){
newHtml += "<div class='news'>" + result[i].content + "</div>";
}
$("#activecontent").append( newHtml );
// Or $("#activecontent").html( newHtml );
// if you want to replace what the page loaded with
});
Now to explain. The first piece of javascript with the .on, what were doing there is binding an event listener to your parent div, #activecontent. We do that because it will always exist in your page. You will be adding and maybe removing divs from that container based on your AJAX call, so instead of having to bind a click (or inline some javascript for every div), you can bind once to the parent, and then delegate that click to '.news'. You can alternatively bind the click to each new div, but delegating is cleaner.
As for the part about loading the JSON and writing it. If you are going to add some stuff to a node's innerHTML, the jQuery way is to use .append(). It's just a shortcut to something like
//vanilla js way
var e = document.getElementById('myThing');
e.innerHTML = e.innerHTML + "Thing I want to append";
// vs jQuery way
$("#myThing").append("Thing I want to append");
//To continue this example, to replace your myThing's html
//vanilla
e.innerHTML = "my new html";
//jQuery
$("#myThing").html("my new html");
Hopefully this clears things up for you. If you are just jumping into jQuery, know that it's not always that it's faster to write than the vanilla javascript, but rather that when you do something like ..html('new stuff');, it's going to use a method that works best with all browsers. So if there's some rogue version of IE out there than wants to use .innerHTMLmsIsNeat instead of .innerHTML, jQuery will sort that for you.

How to append an element to a div which is without id

I want to use javascript to add a link inside a div, this div doesn't have id , it does has a class though:
<div class="details">
<div class="filename">test.xml</div>
<div class="uploaded">25/12/2012</div>
Delete
<div class="compat-meta"></div>
</div>
How to add a link inside the "details" div and above the "delete" link?
The link I want to add is:
Edit
go for jquery, it's simple and clean.
you can grab any element with a particular class say
<div class="className" ></div>
like this
<script>
$('.className');
</script>
now you want to append someother element just before the anchor having delete class, well than you can do this:
$('.delete').before('Edit');
there are other methods also to append an element inside any other element or dom
1. $('.className').append('<div> i will be appended at the bottom of this element</div>');
2. $('.className').after('<div> i will be appended right after this element</div>');
for using jquery, you will need its api, directly use this link in your page or, download the latest jQuery api and use it.
its simpler and easier.
function hasClass(element, className) {
var s = ' ' + element.className + ' ';
return s.indexOf(' ' + className + ' ') !== -1;
}
/**
* from: http://www.dustindiaz.com/getelementsbyclass
*/
function $class(className, context, tag) {
var classElements = [],
context = context || document,
tag = tag || '*';
var els = context.getElementsByTagName(tag);
for (var i = 0, ele; ele = els[i]; i++) {
if (hasClass(ele, className)) {
classElements.push(ele);
}
}
return classElements;
}
then use the $class('delete') to locate the elements, and then prepend new elements
It's always best to search by id, it is most efficient. However if it comes to it, you may find elements by class or tag name as well.
I recommend using jQuery, and changing the existing tag you have:
$('a').attr('href', '#edit_link').text('Edit').removeClass('delete').addClass('edit');
If it is not possible to add an id to the element you're finding, find an element somewhere higher in the tree that has an id, and go from there:
$('#someHigherId > div > a')...
You could use jQuery:
$('div.details a.delete').before('Edit');
You can do it using javascript like this
<script type="text/javascript">
function addtext(what){
if (document.createTextNode){
var link = document.createElement('a');
link.setAttribute('href', '#edit_link');
link.setAttribute('id', 'edit');
link.setAttribute('class', 'edit');
document.getElementsByTagName("div")[0].appendChild(link)
document.getElementById("edit").innerHTML = what;
}
}
</script>
<div class="details" id="mydiv" onClick="addtext('Edit')">
<div class="filename">test.xml</div>
<div class="uploaded">25/12/2012</div>
Delete
<div class="compat-meta"></div>
</div>
Using pure JavaScript:
var div = document.getElementsByClassName('details')[0],
deleteLink = div.getElementsByClassName('delete')[0],
editLink = document.createElement('a');
editLink.textContent = 'Edit';
editLink.className = 'edit';
editLink.href = '#edit_link';
div.insertBefore(editLink, deleteLink);

Categories