How to add/remove a value from stored html - javascript

According to the user navigation to pages, i would like to show appropriate side bars. so I am basically getting html of side bar and putting in empty.
and i am storing the sidebar to object. before i add to object i would like to add an id to side bar. i am trying but not working;
here is my try:
var ob = {};
var catcheBars = {};
var sidebar = $('div.sidebar');
var catchedBar = sidebar;
sidebar.empty();
for(i=1; i <= 5; i++) {
if(!ob.hasOwnProperty(i+'page')) {
ob[i+'page'] = catchedBar;
console.log($(ob[i+'page']).find('button').addClass('sidebar'+i)); //not able to add class
}
}
$("#sideBar").html(ob['1page']); //nothing append to live..
console.log(ob);
my try is not working. when i do the mistake, or what is the correct way?
thanks in advance
Update
Live Demo

I removed the empty() function. it works fine.
here is he updated result
var ob = {};
var catcheBars = {};
var sidebar = $('div.sidebar');
var catchedBar = sidebar;
for(i=1; i <= 5; i++) {
if(!ob.hasOwnProperty(i+'page')) {
ob[i+'page'] = catchedBar;
console.log($(ob[i+'page']).find('button').addClass('sidebar'+i)); //not able to add class
}
}
$("#sideBar").html(ob['1page']); //nothing append to live..
console.log(ob);

Related

How to display HTML class of current node in JS

I have variables which:
display the result (result), and
reference the current node (thisNode).
What do I need to change in my code so that it would display the HTML class?
var thisNode = document.body.firstChild;
var result = document.getElementById("resultOfButton");
result.InnerHTML = thisNode.;
/* Here, in JS are there any ways like displaying the class name,
like nodeClass */
Please give recommendations for my code. There may be some errors. Thank you.
var thisNode = document.body.firstChild;
var result = document.getElementById("resultOfButton");
var block = false;
function buttonDown()
{
if(block == true)
{
thisNode = thisNode.parentElement.firstChild;
block = false;
}
thisNode = thisNode.nextSibling;
result.innerHTML = thisNode.nodeName;
if(thisNode == thisNode.parentNode.lastChild)
{
block = true
}
}
function buttonUp()
{
// not done now...
}
function buttonEnter()
{
thisNode = thisNode.firstChild;
result.innerHTML = thisNode.c;
}
function buttonBack()
{
// not done now...
}
I think you're asking for the className attribute. I copied your first sample and added some code so you can run it on this page. You'll get the second emoji replaced by the class name of the inserted element.
var thisNode = document.getElementById("thisNode"); // document.body.firstChild;
var result = document.getElementById("resultOfButton");
result.innerHTML = thisNode.className; /*Here, in JS are there any ways like displaying the class name, like nodeClass*/
<div id="thisNode" class="sample-class">🙂</div>
<div id="resultOfButton">🙃</div>
Quoting MDN:
"The className property of the Element interface gets and sets the value of the class attribute of the specified element."

I am making a firebase-database list and don't know how to make it remove items from the database

I am pretty new to Javascript, a couple of months in. Essentially, I am trying to make a simple online-based shared shopping-list for a class. I can add to the database, I can show the items as a list, right now my issue is how to remove. I have given the buttons the keys of the database entry they are attached to, as ID, hoping that that would work, but I can't find a way to use the ID. As you can see, i've been testing it by seeing if I can console.log the key, but no luck so far. I've seen a dozen videos and tried dozens of guides, and I hope you can help me; How to I make it so when I click the button, the corresponding entry in the database is deleted? Sorry that the code is a bit of a mess, right now, it is mostly strung together from old code and guides.
var database = firebase.database();
var ref = database.ref('Varer');
ref.on('value', gotData, errData);
function gotData(data){
document.getElementById('Liste').innerHTML = "";
var kbdt = data.val();
var keys = Object.keys(kbdt);
for (var i = 0; i < keys.length; i++){
var k = keys[i];
var kob = kbdt[k].varer;
var btn = document.createElement('button');
var btnText = document.createTextNode('Done')
var opg = document.createElement('li');
var opgnvn = document.createTextNode(kob);
opg.appendChild(opgnvn);
btn.appendChild(btnText);
opg.appendChild(btn);
opg.setAttribute('id', k);
opg.setAttribute('class', 'button');
document.getElementById('Liste').append(opg);
btn.addEventListener('click', function(){
deleteTask(this.id)});
}
}
function errData(err){
console.log('error!');
console.log(err);
}
function deleteTask(id) {
console.log(id);
}
function Indkob() {
var nyVare = document.getElementById('tilfoj').value;
document.getElementById('Liste').innerHTML = "";
var data = {
varer: nyVare
}
var result = ref.push(data);
console.log(result.keys);
}

How to clear innerHTML of spans

I have a basic form in html, when user leave blank fields I show a message in spans that I created via javascript, so far so good. But if I click 'submit' button again and again, the messages are printed again and again Above the message that has already been printed, I mean overlapping.
I tried the element.innerHTML = ''; and this. Maybe I'm implementing it badly since it does not work.
var myForm = document.getElementsByTagName('form')[0];
var formFields = document.getElementsByTagName('label');
myForm.addEventListener('submit', function(){
event.preventDefault();
var statusMessageHTML = [];
// create empty spans
for(i = 0; i < formFields.length; i++){
statusMessageHTML[i] = document.createElement('span');
statusMessageHTML[i].className = 'status-field-message';
formFields[i].appendChild(statusMessageHTML[i]);
}
// print a string in empty spans
for(i = 0; i < formFields.length; i++){
statusMessageHTML[i].innerHTML = "Error Message"
}
return false;
});
PD: I want to solve this using pure javascript.
CODEPEN
To prevent this, you can create and append those spans in advance, and just modify their text when the submit button is clicked.
For example, rearrange your code as following:
var myForm = document.getElementsByTagName('form')[0];
var formFields = document.getElementsByTagName('label');
// create empty spans in advance
var statusMessageHTML = [];
for(var i = 0; i < formFields.length; i++) {
statusMessageHTML[i] = document.createElement('span');
statusMessageHTML[i].className = 'status-field-message';
formFields[i].appendChild(statusMessageHTML[i]);
}
myForm.addEventListener('submit', function(event) {
event.preventDefault();
// change the text of spans
for(var i = 0; i < formFields.length; i++)
statusMessageHTML[i].textContent = 'Error Message';
});
Note:
You have to include corresponding variable name (i.e., event) in the function's parameters before using it.
span.textContent may be preferable to span.innerHTML in your case.
It is pointless to return a value in the addEventListener's callback function. The returned value is simply discarded.
It is a good practice to declare all variables (e.g., i) before using them.
You can also construct those spans directly in HTML, since they are kind of "static" in the structure.
Updated
If I understand it correctly, you prefer:
Create those spans as placeholders when it is the first time the user submits.
Rewrite values in spans when the response of the ajax request is received.
If the submit button is clicked multiple times, just clear previous values in spans, and the following process remains the same.
Then I believe you just need to wrap the whole part in a if-else block:
var myForm = document.getElementsByTagName('form')[0];
var formFields = document.getElementsByTagName('label');
var statusMessageHTML = [];
var isFirstSubmit = true;
myForm.addEventListener('submit', function(event) {
event.preventDefault();
if(isFirstSubmit) {
// create empty spans
for(var i = 0; i < formFields.length; i++) {
statusMessageHTML[i] = document.createElement('span');
statusMessageHTML[i].className = 'status-field-message';
formFields[i].appendChild(statusMessageHTML[i]);
}
isFirstSubmit = false;
} else {
// clear previous values
for(var i = 0; i < formFields.length; i++)
statusMessageHTML[i].textContent = '';
}
});
And rewrite the values when you get the response (possibly wrapped in a callback function, since it is an AJAX request):
function callback(response) {
for(var i = 0; i < formFields.length; i++)
statusMessageHTML[i].textContent = /*values in response*/;
}

Check if team already added

I have a page where you can invite teams. Clicking "Invite teams" makes a popup box appear showing a search input. The search-function is AJAX based. When a team is found through your search word(s), you'll have to click on the team whereupon the team will be showed in a "Invited-teams"-box.
It works in a way that when you "add" the team, a hidden input field is generated containing the team's ID as a value. The problem is that with my current code, it is possible to add the same team as many times as you wish. I should be possible to check, if the team can be found in the hidden-input-data. If it already exists, it should not be possible to add the sane team.
My current javascript-code can be found beneath here. Please notice that I have tried to make the code that checks the team, but it doesn't work.
function addTeam(tid) {
// Grab the input value
var teamName = document.getElementById(tid).innerHTML;
var teamID = document.getElementById(tid).id;
// If empty value
if(!teamName || !teamID) {
alert('An error occured.');
} else {
//Tried to do the "team-adlready-added"-test, but it doesn't work
var stored_teams = $t('#store-teams').getElementsByTagName('input');
for (var i = 0; i < stored_teams.length; i++) {
var stored_team = stored_teams[i];
if(stored_team.value == teamID) {
break;
var team_already_added = 1;
}
alert(team_already_added);
}
if((team_already_added) || team_already_added != 1) {
// Store the team's ID in hidden inputs
var store_team = document.createElement('input');
store_team.type = 'hidden';
store_team.value = teamID;
// Append it and attach the event (via onclick)
$t('#store-teams').appendChild(store_team);
// Create the teams with the value as innerHTML
var div = document.createElement('div');
div.className = 'team-to-invite';
div.innerHTML = teamName;
// Append it and attach the event (via onclick)
$t('#teams').appendChild(div);
}
div.onclick = removeTeam;
}
return false;
}
Thanks in advance.
I just want to give you a hint for a possible solution without html elements.
You can create a new functional object for team:
var Team = function (id, name) {
this.name = name;
this.id = id;
}
Create an array which will contain teams:
var TeamList = [];
Add you Teams:
TeamList.push(new Team(1, "Team 1"));
TeamList.push(new Team(2, "Team 2"));
TeamList.push(new Team(3, "Team 3"));
TeamList.push(new Team(4, "Team 4"));
Write a function which loops trough the list of teams and checks with the id if a team already exists:
function containsTeam(id) {
for (var i = 0; i < TeamList.length; i++) {
if (TeamList[i].id == id) {
return true;
}
}
return false;
}
Just check it:
containsTeam(1); //returns true
containsTeam(5); //returns false
Have a look at the jsFiddle DEMO and open the console to see the output.
EDIT: In addition, to remove an element you can write a function which looks pretty much the same as the containsTeam function. Just use array.splice instead of returning true:
function removeTeam(id) {
for (var i = 0; i < TeamList.length; i++) {
if (TeamList[i].id == id) {
TeamList.splice(i, 1);
}
}
}
And remove a team:
removeTeam(3);
Your variable scope is off.
You declare team already added in the wrong spot.
Declare it with team name and team id and it will get you in the right direction

How do I use a variable in this function?

I've got this problem i can't solve.
I want to make the part that says "aboutMe" a variable called page_name (after the parameter), but I can't get it working...
$(document).ready(function(page_name) {
$.getJSON('../json/text.json', function(obj) {
// fill the title
for(i in obj.titles) {
var id1 = obj.titles[i].id;
var title1 = obj.titles[i].title;
$("#"+id1+"_title").append(title1);
}
// fill the rest of the page
for(i in obj.pages.aboutMe.page_element) {
var id = obj.pages.aboutMe.page_element[i].id;
var title = obj.pages.aboutMe.page_element[i].title;
var content = obj.pages.aboutMe.page_element[i].content;
var left_content = obj.pages.aboutMe.page_element[i].content_left;
var right_content = obj.pages.aboutMe.page_element[i].content_right;
$("#"+id+"_title").append(title);
$("#"+id+"_content").append(content);
$("#"+id+"_left_content").append(left_content);
$("#"+id+"_right_content").append(right_content);
}
for(var i in obj.pages.study) {
}
});
});
Does Anyone know how to solve this?
I would be very gratfull!
What is the error? Try using $(document).ready(function(){}); syntax. It may happen that there is a Jquery conflict. You can also resolve that by JQuery(document).ready(function(){});

Categories

Resources