This is my code so far
var items = [];
function addItems () {
items.push(document.getElementById("txtArea").value);
document.getElementById('txtArea').value = '';
console.log('items = [' + items + ']');
}
function displayItems () {
var tag1 = '<p>',
tag2 = '</p>';
for(var i in items) {
document.write(tag1 + 'Element ' + i + ' = ' + items[i] + tag2);
}
}
<input type='text' id='txtArea'>
<input type="button" value="Add" id="addButton" onclick='addItems()'>
<input type="button" value="Display" id="displayButton" onclick='displayItems()'><hr>
<p id='elements'></p>
In the text field I add numbers that are pushed to an array. When I press display it should display all the elements of that array after the horizontal line, but instead it opens a new page with all of those elements.
What I want is to display elements after the horizontal line in the same page. Could someone please help me?
You need to set the text of paragraph elements
document.getElementById('elements').innerHTML = 'New Value';
instead of
document.write(....)
var items = [];
function addItems() {
items.push(document.getElementById("txtArea").value);
document.getElementById('txtArea').value = '';
console.log('items = [' + items + ']');
}
function displayItems() {
var tag1 = '<p>',
tag2 = '</p>',
str = '';
for (var i in items) {
str += tag1 + 'Element ' + i + ' = ' + items[i] + tag2 + '<br/>';
}
document.getElementById('elements').innerHTML = str;
}
<input type='text' id='txtArea'>
<input type="button" value="Add" id="addButton" onclick='addItems()'>
<input type="button" value="Display" id="displayButton" onclick='displayItems()'>
<hr>
<p id='elements'></p>
document.write() will erase all data in body so you cannot use it after load.
Try to make a text var,
var text = "";
then append in loop
text += tag1 + 'Element ' + i + ' = ' + items[i] + tag2
At the end do
document.body.innerHTML = text;
If i understand your problem correctly, I believe you can do something like this, unfortunately i do not have time to try it myself.
var bodytag = document.getElementsByTagName('body');
for(var i in items) {
var e = document.createElement('p');
e.innerHTML = 'Element ' + i + ' = ' + items[i]
bodytag.appendChild(e);
}
Good luck.
I managed to get it working using this example from w3schools: w3schools.com/jsref/tryit.asp?filename=tryjsref_doc_body_append .
I've deleted the <p id='elements'></p> tag from the html code and modified the displayItems function like this:
function displayItems () {
for(var i in items) {
var e = document.createElement("p");
var t = document.createTextNode('Element ' + i + ' = ' + items[i]);
e.appendChild(t);
document.body.appendChild(e);
}
Thank you all for your help.
Use
document.getElementsByTagName("BODY")[0].html = sth;
instead of:
document.write..
I've created a chat system with javascript. The sent messages are on the right, the received on the left.
Now I want to display them on the bottom (currently they are on the top). But if I set the parent div to the bottom, then both sent and received messages are displayed on one side.
css: Screenshot because this page cannot format my css wow..
https://s15.postimg.org/kav7m3x3v/css_SO.png
win.document.getElementById('input-text-chat').onkeyup = function (e) {
if (e.keyCode != 13) return;
// removing trailing/leading whitespace
this.value = this.value.replace(/^\s+|\s+$/g, '');
var a = new Date();
var b = a.getHours();
var c = a.getMinutes();
var d = a.getSeconds();
if (b < 10) {
b = '0' + b;
}
if (c < 10) {
c = '0' + c;
}
if (d < 10) {
d = '0' + d;
}
var time = b + ':' + c + ':' + d;
if (!this.value.length) return
connection.send('<div class="chat-OutputGET bubbleGET"> <font color="white"> User(' + time + '): ' + this.value + '</font></div>');
console.log(connection.send);
console.log('User (' + time + '): ' + this.value);
appendDIV('<div class="chat-OutputSEND bubble"> <font color="white"> Me (' + time + '): ' + this.value + '</font></div>');
this.value = '';
};
var chatContainer = win.document.querySelector('.chat-output');
function appendDIV(event) {
console.log(event);
var div = document.createElement('div');
div.innerHTML = event.data || event;
chatContainer.appendChild(div);
div.tabIndex = 0;
div.focus();
win.document.getElementById('input-text-chat').focus();
}
connection.onmessage = appendDIV;
}
<div id="chatHtml" style="display: none;">
<link rel="stylesheet" href="style/main.css">
<div id=chatOutput class="chat-output"></div>
<textarea class="form-control" rows="1" id="input-text-chat" placeholder="Enter Text Chat"></textarea>
<div id="chat-container">
</div>
</div>
Its done, i change the position of "chat-output" to absolut and the important point is to set left and right to 0.
The table cell updates correctly to "" (empty) in the changeScore function, but that same cell does not change at all in the editUpdate function when I try to place the new score in there. It just stays empty. Any ideas?
function changeScore(playerKey)
{
var table = document.getElementById("scoreTable");
players[playerKey].score = players[playerKey].oldScore;
table.rows[currentRound - 1].cells[playerKey + 1].innerHTM = '';
document.getElementById('inputArea').innerHTML = '<font size="6">Did <b>' + players[playerKey].name + '</b> take <b>' + players[playerKey].bid + '</b> trick(s)?</font><br /><button value="Yes" id="yesButton" onclick="editUpdate(' + playerKey + ', \'yes\')">Yes</button>    <button value="No" id="noButton" onclick="editUpdate(' + playerKey + ', \'no\')">No</button>';
}
function editUpdate(thePlayerKey, answer)
{
var table = document.getElementById("scoreTable");
players[thePlayerKey].oldScore = players[thePlayerKey].score;
if (answer == "yes"){
**
}else{
**
}
table.rows[currentRound - 1].cells[thePlayerKey + 1].innerHTM = '<font color="' + players[thePlayerKey].font + '">' + players[thePlayerKey].score + '</font>';
document.getElementById('inputArea').innerHTML = '<button onclick="startRound()">Start Round</button>     <button onclick="edit()">Edit Scores</button>';
}
innerHTM should be innerHTML
This:
table.rows[currentRound - 1].cells[playerKey + 1].innerHTM = '';
Should be:
table.rows[currentRound - 1].cells[playerKey + 1].innerHTML = '';
(Same for 2nd function)
Im making a contacts book, and with each new entry it generates a Div with all the information inside. I have gotten as far as giving each generated div a unique ID, and each button generated with the Div a unique ID, however I am having trouble associating the buttons with the div and allowing it to perform functions (such as toggling the visibility of the div).
Any help you can give is greatly appreciated, as I will soon be bald from frustration.
Updated Code with suggestions
The code that generates the DIV and Button:
Contact.prototype.generateDiv = function(){
divid = divid + 1;
buttonid = buttonid + 1;
var control = [];
control[0] = divid;
control[1] = buttonid;
myControls.push(control);
var childDiv =
"<div style='border-style:double;border-width:6px;background-color: #2f4f4f;margin-left:auto;max-width: 700px;margin-right: auto;text-shadow:-1px -1px 1mm #000,1px -1px 1mm #000,-1px 1px 1mm #000,1px 1px 1mm #000;'>" +
this.firstName + " " + this.surname + "<button class='btnForDiv' style='color: black;' id='" + buttonid + "'" + "> Button </button>" +
"<div id='" + divid + "' " + "style='margin-right: auto;margin-left :40px;width: 300px;border-right-style: double;border-right-width:3px;'>" +
"<br>" + "Surname: " + this.surname + "<BR>" + "First Name:" + this.firstName + "<br>" +
"Date Of Birth: " + this.days + "/" + this.months + "/" + this.years + "/" + "<br>" + "Telephone Number: " + this.phone +
"<br>" + "Address: " + this.address + " " + this.post + "<br>" + "Email Address: " + this.email + "<br>" + "Group: " + this.group +
"<br>" + "Days Until Birthday: " + this.daysUntil + "<BR>" + "</div>" + "</div>"
return childDiv ;
}
The entire code
var surnameField,firstNameField,birthdayField, phoneField, addressField, postField, emailField, groupField ; //Declaring variables for the fields
var Contact = function(surname,firstName,date, phone , address , post, email, group){
this.surname = surname ;
this.firstName = firstName ;
this.birthdayDate = new Date (date) ;
this.phone = phone;
this.address= address;
this.email = email;
this.post = post;
this.group = group;
this.selected = false ;
}
var contacts = [];
divid = 0;
buttonid = 1000;
myControls = [];
var getDate = function() {
for (var i= 0, j=contacts.length;i<j;i++){
var y = contacts[i].birthdayDate.getFullYear();
var m = contacts[i].birthdayDate.getMonth();
var d = contacts[i].birthdayDate.getDate();
contacts[i].days = d;
contacts[i].months = m + 1;
contacts[i].years = y ;
var today = new Date() ;
var ty = today.getFullYear();
contacts[i].bdThisYear = new Date(ty,m,d, 0 , 0 , 0);
}
}
var daysUntilBirthday = function(){
for (var i= 0, j=contacts.length;i<j;i++){
var today = new Date() ;
contacts[i].daysUntil = Math.round((contacts[i].bdThisYear - today ) /1000/60/60/24+1);
if (contacts[i].daysUntil <= 0){
contacts[i].daysUntil = contacts[i].daysUntil + 365 ;
}
}
}
Contact.prototype.generateDiv = function(){
divid = divid + 1;
buttonid = buttonid + 1;
var control = [];
control[0] = divid;
control[1] = buttonid;
myControls.push(control);
var childDiv =
"<div style='border-style:double;border-width:6px;background-color: #2f4f4f;margin-left:auto;max-width: 700px;margin-right: auto;text-shadow:-1px -1px 1mm #000,1px -1px 1mm #000,-1px 1px 1mm #000,1px 1px 1mm #000;'>" +
this.firstName + " " + this.surname + "<button class='btnForDiv' style='color: black;' id='" + buttonid + "'" + "> Button </button>" +
"<div id='" + divid + "' " + "style='margin-right: auto;margin-left :40px;width: 300px;border-right-style: double;border-right-width:3px;'>" +
"<br>" + "Surname: " + this.surname + "<BR>" + "First Name:" + this.firstName + "<br>" +
"Date Of Birth: " + this.days + "/" + this.months + "/" + this.years + "/" + "<br>" + "Telephone Number: " + this.phone +
"<br>" + "Address: " + this.address + " " + this.post + "<br>" + "Email Address: " + this.email + "<br>" + "Group: " + this.group +
"<br>" + "Days Until Birthday: " + this.daysUntil + "<BR>" + "</div>" + "</div>"
return childDiv ;
}
var addContact = function(surnameField,firstNameField,birthdayField, phoneField, addressField, postField, emailField, groupField ){
if(surnameField.value){
a = new Contact(surnameField.value, firstNameField.value,birthdayField.value, phoneField.value, addressField.value, postField.value, emailField.value, groupField.value);
contacts.push(a);
}else{ alert("Please complete all fields")}
}
var clearUI = function(){
var white = "#fff";
surnameField.value = "";
surnameField.style.backgroundColor = white;
firstNameField.value = "";
firstNameField.style.backgroundColor = white;
birthdayField.value="";
birthdayField.style.backgroundColor = white;
phoneField.value = "";
phoneField.style.backgroundcolor = white;
addressField.value = "";
addressField.style.backgroundcolor = white;
postField.value = "";
postField.style.backgroundcolor = white;
emailField.value = "";
emailField.style.backgroundcolor = white;
groupField.value="";
groupField.style.backgroundcolor = white;
}
var updateList = function(){
divid = 0;
buttonid = 1000;
myControls = []
var tableDiv = document.getElementById("parentDiv"),
cDiv = "<BR>" + "<div align='center'> Click a contact to expand</div>" ;
for (var i= 0, j=contacts.length;i<j;i++){
var cntct = contacts[i];
cDiv += cntct.generateDiv();
}
tableDiv.innerHTML = cDiv;
getDate();
daysUntilBirthday();
saveContacts();
}
var add = function(){
;
addContact(surnameField,firstNameField,birthdayField, phoneField, addressField, postField, emailField, groupField);
clearUI();
daysUntilBirthday();
getDate();
updateList();
};
var saveContacts = function(){
var cntcts = JSON.stringify(contacts);
if (cntcts !==""){
localStorage.contacts = cntcts;
}else{
alert("Could not save contacts");
}
}
var loadContacts = function(){
var cntcts = "";
if(localStorage.contacts !== undefined){
cntcts = localStorage.contacts;
contacts = JSON.parse(cntcts);
var proto = new Contact();
for (var i=0; i<contacts.length; i++){
var cntct = contacts[i]
cntct.__proto__ = proto;
cntct.birthdayDate = new Date(cntct.birthdayDate);
}
}
}
var clearContacts = function(){
contacts = [];
updateList();
}
//var periodUpdate = function(){
// setInterval(updateList, 10000);
//}
window.onload = function(){
loadContacts();
updateList();
surnameField = document.getElementById("surname");
firstNameField = document.getElementById("firstName")
birthdayField = document.getElementById("birthday");
phoneField = document.getElementById("phone");
addressField = document.getElementById("address");
postField = document.getElementById("post");
emailField = document.getElementById("email");
groupField = document.getElementById("group");
addButton = document.getElementById("addButton");
addButton.onclick = add;
delButton = document.getElementById("delButton");
delButton.onclick = clearContacts;
clearUI();
// periodUpdate();
}
The HTML
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="contacts.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="jquery-1.8.3.min.js">
$(document).ready(function(){
(".btnForDiv").on("click", function(){
// get the ID of the button
var id = $(this).prop("id");
var divid;
// now find the div Id related to this button
for (var i = 0, len = myControls.length; i < len; i++){
if (myControls[i][1] == id){
divid = myControls[i][0];
break;
}
}
// you now have the div,so toggle it.
$("#" + divid).toggle();
});
});
</script>
<div><title>Contacts Book</title></div>
</head>
<body>
<div class="information">
<heading><h1>Contacts Book</h1></heading>
</div>
<p><div class="information">Enter the contacts details below and click Add or select to view an existing contact.</div></p>
<hr>
<div class="entrydiv">
<table class="entryforms">
<br>
<tr>
<td>Surname</td><td><input type="text" class="inputboxes" id="surname" /></td>
</tr>
<tr>
<td>First Name</td><td><input type="text" class="inputboxes" id="firstName" /></td>
</tr>
<tr>
<td>Birthday</td><td><input type="date" class="inputboxes" id="birthday" /></td>
</tr>
<tr>
<td>Phone Number</td><td><input type="text" class="inputboxes" id="phone"></textarea></td>
</tr>
<tr>
<td>Email Address</td><td><input type="text" class="inputboxes" id="email" /></td>
</tr>
<tr>
<td>Address</td><td><input type="text" class="inputboxes" id="address"/></td>
</tr>
<tr>
<td>Postcode</td><td><input type="text" class="inputboxes" id="post" /></td>
</tr>
<tr>
<td>Group</td><td><select class="inputboxes" id="group"/>
<option value="Business">Business</option>
<option value="Educational">Educational</option>
<option value="Friend">Friend</option>
</td>
</tr>
</table>
<br>
<button id="addButton">Add Contact</button>
<button id="delButton">Delete Contacts</button>
</div>
<hr>
<div class="tablediv">
<h2 class="information" align="center">Contacts</h2>
<div id="parentDiv"></div>
</div>
</body>
</html>
The Solution
First of all massive thanks to Darren for his advice, which turns out to be spot on (with minor change)
First error I made was inserting jquery, I had
<script src="jquery-1.8.3.min.js">
//code
</script>
When I needed
<script src="jquery-1.8.3.min.js"></script>
<script>
//code
</script>
So that very minor mistake held me back for a while.
Secondly I used:
$(document).on('click','.btnForDiv',function(){
To call the Onclick event for my btnForDiv class buttons and the rest was all Darren :)
Thanks again
You could do a few things here.
One idea would be to store your generated div and button ID's in an array. You can then search this array for a given button ID to find its corresponding div.
For example (not tested...)
// outside your generatedDiv method
var myControls = new Array();
// then inside your generatedDiv method
var control = new Array();
control[0] = divId;
control[1] = buttonId;
myControls.push(control);
When you click your button you can grab its ID then search through the myControls array and look for the corresponding div
you could do a single function in jQuery to handle all the click for all of your generated buttons.
again (not tested) - give all your buttons a class, for example btnForDiv
$(document).ready(function(){
$(".btnForDiv").click(function(){
// get the ID of the button
var id = $(this).prop("id");
var divId;
// now find the div Id related to this button
for (var i = 0, len = myControls.length; i < len; i++){
if (myControls[i][1] == id){
divId = myControls[i][0];
break;
}
}
// you now have the div,so toggle it.
$("#" + divId).toggle();
});
});
I'm not 100% sure what your question was, though took a stab in the dark to help..
UPDATE
Because your div's are generated and added to the DOM dynamically you may have to use on instead of click - this will bind the click event to dynamic elements.
So try this:
$(".btnForDiv").on("click", function(){
// get the id.... etc...
});
also, make sure you did add the class btnForDiv to your dynamically generated buttons
this.firstName + " " + this.surname + "<button style='color: black;' id='" + buttonid + "b'" + " class='btnForDiv'> Button </button>" +
This is my jsp code where I am trying to push some data in javaScript array.
<%
int proListSize = proList.size();
ProfileDAO proDAO = null;
for(int i = 0, j=1; i < proListSize; i++){
proDAO = (ProfileDAO)proList.get(i);%>
entireArray.push(<%= proDAO.getNetworkmapId()%> + ":"+<%=proDAO.getAssetId()%> + ":" + <%= proDAO.getCode()%>);
<%} %>
And this is the function where I am trying to use it by using pop function.
function GenDemographicTag() {
var ptag = "<!-- Begin "+networkNameToUpperCase+" -->\n" ;
var t = "";
if (WhiteTagLabelDomain) {
ptag += "<iframe src=\"http://"+WhiteTagLabelDomainTrim+"/jsc/"+folderName+"/dm.html?";
} else {
ptag += "<iframe src=\"http://"+cdnName+"/jsc/"+folderName+"/dm.html?";
}
ptag += "n="+networkId+";";
for(var i = 0;i< entireArray.length;i++){
var combinedString = entireArray.splice(1,1);
var rightSide = combinedString.split(':')[0];
var middle = combinedString.split(':')[1];
var leftSide = combinedString.split(':')[2];
t = "";
if ( $("proElementEnable_"+rightSide) && $("proElementEnable_"+leftSide).checked) {
if ( middle == "1") {
if ( $("zip").value.length <= 0) {
t = "0";
} else {
t = $("zip").value;
}
} else if ( $("targetList_"+rightSide) && $("targetList_"+rightSide).length > 0 && $("targetList_"+rightSide).options[0].value != "-1") {
t = makeProelementList($("targetList_"+rightSide));
}
ptag += leftSide+"=" + t+ ";";
}
proDAO = null;
}
ptag += "\" frameborder=0 marginheight=0 marginwidth=0 scrolling=\"no\" allowTransparency=\"true\" width=1 height=1>\n</iframe>\n<!-- end "+networkNameToUpperCase+" -->\n";
document.forms[0].tag.value = ptag;
}
Basically I am trying to get the data from proList and store it in javaScript array(entireArray)...so that I can use in the javascript function..but after doing the above I get a javaScript error as follow:
entireArray.push(3 + ":"+3 + ":" + d3);
entireArray.push(185 + ":"+5 + ":" + d4);
entireArray.push(2 + ":"+2 + ":" + d2);
entireArray.push(186 + ":"+5 + ":" + d9);
entireArray.push(183 + ":"+5 + ":" + d6);
entireArray.push(184 + ":"+5 + ":" + d7);
entireArray.push(187 + ":"+5 + ":" + da);
entireArray.push(445 + ":"+5 + ":" + db);
Reference Error:d3 is not defined.
what is the exact problem..?
The return type of splice is an ARRAY , so you can try following code
var combinedString = entireArray.splice(1,1);
var rightSide = combinedString[0].split(':')[0];
var middle = combinedString[0].split(':')[1];
var leftSide = combinedString[0].split(':')[2];
d3 should be in quotes. "d3"
You need to put the out of JSP in quotes.
entireArray.push(<%= proDAO.getNetworkmapId()%> + ":"+<%=proDAO.getAssetId()%> + ":" + '<%= proDAO.getCode()%>');