I am using ReactJS and I am creating a button "remove" in a method called showData() and appending it to a row in a table of people.
I am setting its attribute onclick to my method removePerson() implemented in the same class of the method showData().
This is all good until I click on the button "remove" - then an error shows:
ReferenceError: removePerson() is not defined at HTMLButtonElement.onclick
This is my code:
showData() {
let localStoragePersons = JSON.parse(localStorage.getItem("personsForms"));
persons = localStoragePersons !== null ? localStoragePersons : [];
let table = document.getElementById('editableTable');
let x = table.rows.length;
while (--x) {
table.deleteRow(x);
}
let i = 0;
for (i = 0; i < persons.length; i++) {
let row = table.insertRow();
let firstNameCell = row.insertCell(0);
let lastNameCell = row.insertCell(1);
let birthdayCell = row.insertCell(2);
let salaryCell = row.insertCell(3);
let choclatesCell = row.insertCell(4);
let genderCell = row.insertCell(5);
let workTypeCell = row.insertCell(6);
let hobbiesCell = row.insertCell(7);
let descriptionCell = row.insertCell(8);
let colorCell = row.insertCell(9);
firstNameCell.innerHTML = persons[i].firstName;
lastNameCell.innerHTML = persons[i].lastName;
birthdayCell.innerHTML = persons[i].birthday;
salaryCell.innerHTML = persons[i].salary;
choclatesCell.innerHTML = persons[i].Choclates;
genderCell.innerHTML = persons[i].Gender;
workTypeCell.innerHTML = persons[i].workType;
hobbiesCell.innerHTML = persons[i].Hobbies;
descriptionCell.innerHTML = persons[i].Description;
colorCell.innerHTML = persons[i].favoriteColor;
colorCell.style.backgroundColor = persons[i].favoriteColor;
let h = persons[i].ID;
let removeButton = document.createElement('button');
removeButton.setAttribute('onclick', 'removePerson(' + h + ')')
removeButton.innerHTML = 'Remove';
row.appendChild(removeButton);
}
}
I tried to change the code
removeButton.setAttribute('onclick', 'removePerson(' + h + ')');
to
removeButton.onclick = this.removePerson(h);
but everyTime the "showData()" method runs this method "removePerson()" run also and i don't want this to happen.
removePerson(ID) {
alert(ID);
let table = document.getElementById('editableTable');
if (persons.length === 1) {
table.deleteRow(1);
persons.pop();
localStorage.setItem("personsForms", JSON.stringify(persons));
}
let target;
let i;
for (i = 0; i < persons.length; i++) {
if (persons[i].ID === ID) {
target = persons[i].firstName;
persons.splice(i, 1); break;
}
}
for (i = 1; i < table.rows.length; ++i) {
let x = table.rows[i];
if (x.cells[0].innerHTML === target) {
table.deleteRow(i); break;
}
}
let temp = [];
let j = 0;
for (i = 0; i < persons.length; ++i) {
if (persons[i] !== null) {
temp[j++] = persons[i];
}
}
persons = temp;
localStorage.clear();
localStorage.setItem("personsForms", JSON.stringify(persons));
this.showData();
}
When you set a variable to some value, the value is computed first.
Hence, when you write removeButton.onclick = this.removePerson(h); the right side of the equation is evaluated first.
You can wrap it with a fat-arrow function, so that the function that will be called upon user click would be the function that calls this.removePerson(h). This way its value is a lambda function, and not the actual value of this.removePerson(h):
removeButton.onclick = () => this.removePerson(h);
I have a shopping Cart on my first page and all the items that have been selected I want it to be shown when user go to the other page.
I'm new in javascript that's why I couldn't figure out how to save those data in local storage. The main thing for me now is how to save the quantity that is being incremented.
NOTE: I'm using one script for two pages.
// this below function is executed when user on page ONE click on the button the quantity increase.
function addtocartbtnclicked(event) {
var button = event.target;
var shopitem = button.parentElement.parentElement;
var title = shopitem.querySelectorAll('h1')[0].innerText;
var price = shopitem.querySelectorAll('.card .price')[0].innerText;
var imgsrc = shopitem.querySelectorAll('.card .my-img')[0].src;
console.log(title, price, imgsrc);
additemtocard(title, price, imgsrc);
updatetotal();
quantityupdate();
}
// this function increase the quantity
function quantityupdate() {
var div = document.querySelectorAll('.each-cart-row');
var qtytotal = 0;
for (var i = 0; i < div.length; i++) {
var card = document.querySelectorAll('.add-to');
card = 1;
qtytotal = qtytotal + card;
}
console.log(qtytotal);
var count = document.querySelector('.totalqty').innerText = qtytotal;
}
var jsonStr = JSON.stringify(quantityupdate());
localStorage.setItem("cart", jsonStr);
// this function is for page TWO where another item will be added when the button is clicked
function addtocartbtnclickedpagetwo() {
var pageimg = document.querySelectorAll('.exzoom_img_ul img')[0].src;
var pagetitle = document.querySelector('#upper-area h3').innerText.slice(62);
var pageprice = document.querySelector('#last-list #product-total').innerText;
var pageqty = document.querySelector('#myform #input-number').value;
console.log(pageimg, pagetitle, pageprice, pageqty);
addtocartitempage(pageimg, pagetitle, pageprice, pageqty);
updatetotal();
var cartValue = document.querySelector('.totalqty')
cartValue = localStorage.getItem("cart");
var cartObj = JSON.parse(cartValue);
}
try to edit quantityupdate function so it actually saves qtytotal variable value to local storage:
function quantityupdate() {
var div = document.querySelectorAll('.each-cart-row');
var qtytotal = localStorage.getItem( "cart") || 0;
for (var i = 0; i < div.length; i++) {
var card = document.querySelectorAll('.add-to');
card = 1;
qtytotal = qtytotal + card;
}
localStorage.setItem( "cart", qtytotal);
var count = document.querySelector('.totalqty').innerText = qtytotal;
return
}
This code below is a javascript code to change texts and background properties from the body tag at the same time when the browser is clicked. I've just followed rules in w3school.com, actually, I'm doing the same as the examples do, but mine won't work and I've failed to find my fault. plz, help me.
var helloDiv = document.createElement("div");
var helloText = document.createTextNode("hi.");
helloDiv.appendChild(helloText);
var bodyntext = document.getElementsByTagName("body").appendChild(helloDiv);
var complementary = new Array();
var j = 0;
window.onclick = function(){
var background_color;
var body = document.getElementsByTagName("body")[0];
// var color = new Array();
var result = null;
var number = Math.round(Math.random()*0xFFFFFF);
for(var i = 0; i > 3; i++)
{
complementary[i] = (255-(number.slice(j,j+1).toString(10))).toString(16);
j = j + 2;
}
var clnumber = (complementary[0]+complementary[1]+complementary[2]).toString(16);
body.style.backgroundColor = "#"+ number.toString();
bodyntext.style.color = "#"+ clnumber.toString();
}
Here's your problem
var bodyntext = document.getElementsByTagName("body").appendChild(helloDiv);
Please note that the javascript functions that have plural names often return arrays which is the case here
document.getElementsByTagName("body") returns an array and you are trying to perform an invalid action, that is append child, to this array. You need to access an element using index and then perform this action.
so using
var bodyntext = document.getElementsByTagName("body")[0].appendChild(helloDiv); should fix your problem.
Use document.getElementsByTagName("body")[0] to achieve expected result, as getElementsByTagName() method returns a collection of all elements in the document with the specified tag name, as a NodeList object.
var helloDiv = document.createElement("div");
var helloText = document.createTextNode("hi.");
helloDiv.appendChild(helloText);
var bodyntext = document.getElementsByTagName("body")[0].appendChild(helloDiv);
var complementary = new Array();
var j = 0;
window.onclick = function(){
var background_color;
var body = document.getElementsByTagName("body")[0];
// var color = new Array();
var result = null;
var number = Math.round(Math.random()*0xFFFFFF);
for(var i = 0; i > 3; i++)
{
complementary[i] = (255-(number.slice(j,j+1).toString(10))).toString(16);
j = j + 2;
}
var clnumber = (complementary[0]+complementary[1]+complementary[2]).toString(16);
body.style.backgroundColor = "#"+ number.toString();
bodyntext.style.color = "#"+ clnumber.toString();
}
codepen - https://codepen.io/nagasai/pen/NLBXJE
Please refer this link for more details - https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName
I just change appendChild to document.body.appendChild(helloDiv) and added ID attribute for that div:
var helloDiv = document.createElement("div");
helloDiv.id = "myDIV";
document.body.appendChild(helloDiv);
var helloText = document.createTextNode("Click me");
helloDiv.appendChild(helloText);
var complementary = new Array();
var j = 0;
window.onclick = function(){
var background_color;
var body = document.getElementsByTagName("body")[0];
var helloText = document.getElementById("myDIV");
// var color = new Array();
var result = null;
var number = Math.round(Math.random()*0xFFFFFF);
for(var i = 0; i > 3; i++)
{
complementary[i] = (255-(number.slice(j,j+1).toString(10))).toString(16);
j = j + 2;
}
var clnumber = (complementary[6]+complementary[1]+complementary[2]).toString(16);
var clnumber2 = (complementary[0]+complementary[2]+complementary[6]).toString(11);
body.style.backgroundColor = "#"+ number.toString();
helloText.style.color = "#"+number.toString();
}
I'm trying to change the options that appear in my select box named session when a certain option is picked in my select box named movie.
Here's the script I've got so far.
<script>
var optionList = document.getElementsByName("movie")[0];
var movieList = ["AC", "CH", "AF", "RC"];
for(var i = 0; i < movieList.length; i++){
var movie = movieList[i];
var option = document.createElement("option");
option.textContent = movie;
option.value = movie;
optionList.appendChild(option);
}
</script>
<script>
var sessionList = document.getElementsByName("session")[0];
var actionSession = ["WED-09", "THU-09", "FRI-09", "SAT-09", "SUN-09"];
var childrenSession = ["MON-01", "TUE-01", "WED-06", "THU-06", "FRI-06", "SAT-12", "SUN-12"];
var foreignSession = ["MON-06", "TUE-06", "SAT-06", "SUN-06"];
var romanticSession = ["MON-09", "TUE-09", "WED-01", "THU-01", "FRI-01", "SAT-06", "SUN-06"];
if(document.getElementsByName("movie")[0].value === movieList[0])
{
for(var i = 0; i < actionSession.length; i++){
var session = actionSession[i];
var option = document.createElement("option");
option.textContent = session;
option.value = session;
sessionList.appendChild(option);
}
}
</script>
Consider changing the Sessions to an object, like so:
var sessions = {
"AC": ["WED-09", "THU-09", "FRI-09", "SAT-09", "SUN-09"],
"CH": ["MON-01", "TUE-01", "WED-06", "THU-06", "FRI-06", "SAT-12", "SUN-12"],
"AF": ["MON-06", "TUE-06", "SAT-06", "SUN-06"],
"RC": ["MON-09", "TUE-09", "WED-01", "THU-01", "FRI-01", "SAT-06", "SUN-06"]
}
This way, you can use the onchange of your select tag to get the value of the selected option and reference the list of sessions for the appropriate movie list as such:
var category = document.getElementByName("movie").value;
var currentSession = sessions[category];
for(var i = 0; i < currentSession.length; i++){
var session = currentSession[i];
var option = document.createElement("option");
option.textContent = session;
option.value = session;
sessionList.appendChild(option);
}
Objects in javascript can be referenced as "key" => "value" pairs simply by following the syntax:
object = { "key": value }, and value's type can be anything - even another Object!
You can even declare object keys like such:
var sessions = {};
sessions['AC'] = [...];
sessions['CH'] = [...];
sessions.AF = [...];
sessions.RC = [...];
That's right - all of the above declarations can be referenced as sessions['xx']
Hope this simplifies things a bit.
You could create a dictionary mapping elements of movieList to lists of <option> elements, maybe?
You might call the dictionary sessionOptions. You would then change all the children of #session at once - so this would go in your onchange handler for sessionList:
var sessionList = document.getElementsByName("session")[0];
var chosenMovie = "..."; // "AC", for instance
// Remove all elements from sessionList
while(sessionList.firstChild) {
sessionList.removeChild(sessionList.firstChild);
}
// Add the chosen movie options
var chosenMovieOptions = sessionOptions[chosenMovie];
for(var i = 0; i < chosenMovieOptions.length; i++) {
sessionList.appendChild(chosenMovieOptions[i]);
}
You would also want to make a mapping of movie codes to session lists:
var SESSION_LISTS = {
"AC": ["WED-09", "THU-09", "FRI-09", "SAT-09", "SUN-09"],
"CH": ["MON-01", "TUE-01", "WED-06", "THU-06", "FRI-06", "SAT-12", "SUN-12"],
"AF": ["MON-06", "TUE-06", "SAT-06", "SUN-06"],
"RC": ["MON-09", "TUE-09", "WED-01", "THU-01", "FRI-01", "SAT-06", "SUN-06"]
};
Then, to build sessionOptions, for each "session string list" (such as actionSession), you would loop through the session list and create elements:
var currentSession = "..."; // currentSession is the current session list - "AC", for instance
var currentSessionOptions = SESSION_LISTS[currentSession];
sessionOptions[currentSession] = [];
for(var i = 0; i < currentSessionOptions.length; i++){
var session = currentSessionOptions[i];
var option = document.createElement("option");
option.textContent = session;
option.value = session;
sessionOptions[currentSession].append(option);
}
But then you would do this for every sublist in SESSION_LISTS, so you would put this code in some initializer function:
var sessions = Object.keys(SESSION_LISTS);
for(var i = 0; i < sessions.length; i++) {
currentSession = sessions[i];
// the code snippet above
}
i am trying to make a random name picker from an array of names taken from localstorage which seems that the error isn't popping up when i inspect it with google chrome.
Here's my code:
function getUserData() {
var Detail = localStorage.getItem("Detail");
if (Detail == null) {
Detail = []; // on new computer, create the local storage item } else {
Detail = JSON.parse(Detail); // convert from string to array
}
for (var i = 0; i < Detail.length; i++) { // loop through the array
var row = document.getElementById("Detail").insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
cell1.innerHTML = Detail[i].name;
cell2.innerHTML = Detail[i].admin;
cell3.innerHTML = Detail[i].email;
cell4.innerHTML = Detail[i].contact;
cell5.innerHTML = Detail[i].country;
}
}
function NamePicker() {
var Detail = localStorage.getItem("Detail");
if (Detail == null) {
Detail = []; // on new computer, create the local storage item
} else {
Detail = JSON.parse(Detail); // convert from string to array
}
// copy names
var nameArray = [];
for (var i = 0; i < Detail.length; i++) { // loop through the array
nameArray[i] = Detail[i].name;
}
for (var i = 0; i < Detail.length; i++) { // loop through the array
// get a number from random num generator %numArray.length
name = nameArray[num];
while (nameArray.length < 11) {
var randomnumber = Math.max(Math.ceil(Math.random() * 11))
var found = false;
for (var i = 0; i < nameArray.length; i++) {
if (name[i] == randomnumber) {
found = true;
break
}
}
if (!found) name[nameArray.length] = randomnumber;
}
// Display using modal
alert(name);
// remove using splice(num, 1);
name.splice(num, 1);
document.getElementById("Detail").innerHTML = name;
}
}
the problem is that it seems that num isn't removing the name from the list and alert function isn't popping up...
i really appreciate the help thanks in advance...
I found a couple of problems in you second function; you are using the local variable i in three for loops, and I think in one of them you meant to use num. Also, I changed Detail.length to nameArray.length in the second for loop since you are going through the nameArray. I also change the third for loop to use z instead of i.
function NamePicker() {
var Detail = localStorage.getItem("Detail");
if (Detail == null) {
Detail = []; // on new computer, create the local storage item
} else {
Detail = JSON.parse(Detail); // convert from string to array
}
// copy names
var nameArray = [];
for (var i = 0; i < Detail.length; i++) { // loop through the array
nameArray[i] = Detail[i].name;
}
for (var num = 0; num < nameArray.length; num++) { // loop through the array
// get a number from random num generator %numArray.length
name = nameArray[num];
while (nameArray.length < 11) {
var randomnumber = Math.max(Math.ceil(Math.random() * 11))
var found = false;
for (var z = 0; z < nameArray.length; z++) {
if (name[z] == randomnumber) {
found = true;
break
}
}
if (!found) name[nameArray.length] = randomnumber;
}
// Display using modal
alert(name);
// remove using splice(num, 1);
name.splice(num, 1);
document.getElementById("Detail").innerHTML = name;
}
}
Hope that helps!