JavaScript Return from Nested Array WITHOUT specified Keys

I’m trying to write a function that will return an object omitting key(s) from a possibly nested items in an array. I found a close answer on a different question, but not quite what I was looking for. Any feedback would be greatly appreciated! Here is the code I’m tinkering with right now;

function omit(obj, keys) {
    let newObj = [];
    for (let i of obj) {
        if (i === keys) {
            //do nothing
        } else {
            //newObj.push[i]; nope?
            return newObj;
        }
        //return newObj;
    }
}

Material UI, textfield loses focuses only when ‘a’ or ‘s’ is pressed

I’m really confused on what’s going on with my code. I have a Menu, that has list of avatars, and then another button in list. The last button, is another menu, that pops up a TextField. For some reason in the Textfield, Ever keystroke is recorded in the input, except when I hit ‘a’. It automatically unfocuses. I’m not sure what’s going on. Any insight on what’s going wrong?

Menu

enter image description here

   return (<div id={row.name + "-" + "div"}>
        <IconButton className="hideAddIcon"
            id={row.name + "-" + "basic-button"}
            key={row.name + "-" + "icon"}
            aria-haspopup="true"
            aria-controls="basic-menu"
            aria-haspopup="true"
            aria-expanded={open ? 'true' : undefined}
            onClick={(e) => handleClick(e, row.name)}
        >
            <AddCircleOutlineIcon fontSize="medium" />
        </IconButton>
        <Menu
            style={{
                paddingBottom: '0px'
            }}
            id={row.name + '-menu'}
            key={row.name + '-menu-icon'}
            anchorEl={anchorEl && anchorEl[row.name]}
            open={Boolean(anchorEl && anchorEl[row.name])}
            onClose={handleClose}
            MenuListProps={{
                'aria-labelledby': 'basic-button',
            }}
        >
            {
                Array.from(selectionMenuData.keys()).map((key, index) => {
                    return <MenuItem key={row.name + '-' + index} value={row.name} style={{ maxHeight: '55px' }} onClick={(e) => addPersonToList(row, selectionMenuData.get(key))}>
                        {(() => {
                            switch (row.sourceType) {
                                case 'People':
                                    return (
                                        <ListItemAvatar>
                                            <Image src={selectionMenuData.get(key).Avatar} className={classes.peopleMenuPicture} />
                                        </ListItemAvatar>
                                    );
                                case 'Seller Competition':
                                    return (
                                        <ListItemAvatar style={{
                                            minWidth: '90px', display: 'flex',
                                            justifyContent: 'center',
                                        }}>
                                            <Image src={selectionMenuData.get(key).Logo} />
                                        </ListItemAvatar>
                                    )
                            }
                        })()}
                        <ListItemText>{key}</ListItemText>
                    </MenuItem>
                })
            }
            {(row.sourceType === 'People' || row.sourceType === 'Seller Competition') ?
                <MenuItem key="addNewPersonMenu" onClick={(e) => secondMenuClick(e, 'addPerson')}>
                    <ListItemAvatar style={{
                        minWidth: '90px', display: 'flex',
                        justifyContent: 'center',
                    }} >
                        <AddCircleOutlineIcon sx={{ width: row.sourceType === 'Seller Competition' ? '53px' : '84px' }} />
                    </ListItemAvatar>
                    <ListItemText >
                        {menuText}
                    </ListItemText>
                    <Popover
                        id="add-person-menu"
                        anchorEl={anchorEl && anchorEl['addPerson']}
                        open={Boolean(anchorEl && anchorEl['addPerson'])}
                        onClose={(e) => handleCloseDialog(e)}
                        MenuListProps={{
                            'aria-labelledby': 'add-person-button',
                        }}
                        anchorOrigin={{
                            vertical: 'top',
                            horizontal: 'left',
                        }}
                        transformOrigin={{
                            vertical: 'top',
                            horizontal: 'left',
                        }}
                    >
                        <div style={{ paddingLeft: 10, paddingRight: 10, width: '20em' }} tabIndex={0} >
                            <TextField id="outlined-basic" label="LinkedIn URL" id='add-person-name' autoFocus
                                variant="outlined" fullWidth autoComplete='off' type='text' name='linkedinUrl'
                                placeholder="Enter LinkedIn URL..." onKeyDown={(e) => submitNewPerson(e, row)} />
                            {/* <input type="text" id="submitPeople" name="addPeople"></input> */}

                            {console.log(anchorEl)}
                        </div>
                    </Popover>
                </MenuItem> : <div>Not Added</div>
            }
        </Menu>
    </div>)
}

how to store Node js db response into a variable

I have a pcs.db with post codes and their geolocation coordinates. I am trying to extract locations from given code name.

I am able to console log the result, but am unable to store the result into a variable.

I tried .then(function) as I believe db each returns a promise. 4 hours later I am in the same spot I started in. Please help.

const sqlite3 = require('sqlite3').verbose()

    const getCoords = function (postcode) {
      let db = new sqlite3.Database('./pcs.db');
      let sql = `SELECT long, lat FROM postcodes WHERE code='${postcode}'`;

      db.each(sql, [], (err, row) => {
        if (err) {
          throw err;
        }
         console.log(row);
      });
      
      // close the database connection
      db.close();
      }

      getCoords('SM4 4')
        

eventListener is firing multiple times before the refresh JS

I’m making a simple submit button for an email form,when clickling on the submit button and the email is valid,it changes the state of the button from “Subscribe” to Unsubscribe and it hides the form. Till here everything is good,but the problem is that when i click the submit button,it does what i need but after i enter a valid email and it changes the state of the button,the oposite action isnt done and it continues to send the email to localstorage,instead of removing it.
Here i add a non valid email :
enter image description here
And in console log i have this email.
Here i add a valid email without refreshing the page :

enter image description here

And now,when i click unsubscribe,it should remove the email from localStorage and return the form and the state of the button,but instead,it makes the submit action..:
enter image description here

What should i do? I am new in JS and here i use only vanilla js.

The code that use the submit button:

document.querySelector('form').addEventListener('submit', function (e) {
e.preventDefault()
console.log(inputForm.value)
localStorage.setItem('Email', inputForm.value)
subscribeEmail(inputForm.value);
 })

The code below is used to mentain the state of the button when refreshing the page:

const unsubscribeToggle = localStorage.getItem('unsubscribeToggle')
  if (unsubscribeToggle === 'Subscribed') {
    getUnsubscribe()
    document.querySelector('form').addEventListener('click', function (e) {
      e.preventDefault()
      getSubscribe()
      localStorage.removeItem('Email')
    })
  } else {
    getSubscribe()
  }
}

Below is the code that changes the state of the button :

 export const getUnsubscribe = () => {
    const subscribeBtn = document.getElementById('subscribeButton')
    subscribeBtn.setAttribute('value', 'Unsubscribe')
    document.getElementById('emailForm').style.display = 'none'
    localStorage.setItem('unsubscribeToggle', 'Subscribed')
}

export const getSubscribe = () => {
    const subscribeBtn = document.getElementById('subscribeButton')
    subscribeBtn.setAttribute('value', 'Subscribe')
    document.getElementById('emailForm').style.display = 'block'
    localStorage.setItem('unsubscribeToggle', 'Unsubscribed')
}


export const subscribeEmail = (email) => {
    if (validateEmail(email) == true) {
        getUnsubscribe();
    } else if (validateEmail == false) {
        getSubscribe();
    }

And here is the validation function :

const VALID_EMAIL_ENDINGS = ['gmail.com', 'outlook.com', 'yandex.ru']

export const validateEmail = (email) => {
  if (VALID_EMAIL_ENDINGS.some(v => email.includes(v))) {
  return true
  } else {
  return false
  }
}

export { VALID_EMAIL_ENDINGS as validEnding }

I dont understand what is wrong,or is this normally to happen..It gives me the oportunity to “unsubscribe” only after refreshing the page,but i want to subscribe and unsubscribe multiple times without the need of refresh.

can’t get value from onclick function javascript

I have a function where I am trying to get a value from an onclick event.

Here is the element attribute that gives the function to the element:

listcontainer.setAttribute('onmousedown',"knowbe4campaignspecific(this)")

Here is the function code:

function knowbe4campaignspecific(ele){
    console.log(ele.value)}

However it will say undefined in the developer console.

If I just print the element by itself it will show the value inside so I must be missing something basic.

function knowbe4campaignspecific(ele){
    console.log(ele)}

##RESULTS##
<ul value="183085" onmousedown="knowbe4campaignspecific(this)" class="ms-List"></ul>

Let me know if anything else is needed and I will update this post. Thanks!

How do I add “Syntax Error” if the numbers aren’t compatible on my html/javascript/css calculator?

So, I wanted to make it so that if, for some reason, people mistyped/misclicked something on my calculator, it would show a syntax error. However, I do not know how to do so.

What I mean by “mistyped” is when someone might have accidentally written something like:

10 + / 10

when they actually wanted to write 10 + 10.

Currently, my calculator just shows the equation inputted when there is an error, and doesn’t do anything else. I just want to add the function for efficiency’s sake.

<html>
<head>
<script>
function dis(val)
{
document.getElementById("result").value+=val 
}

function solve()
{

let x = document.getElementById("result").value
let y = eval(x)
document.getElementById("result").value = y 
}

function clr()
{
document.getElementById("result").value = " "
}

</script>
<style>
.title{
margin-bottom: 10px;
text-align:center;
width: 100%;
color:Black;
border: solid gray 2px;
font-size:30px
}

input[type="button"]
{
background-color:gray;
color: black;
border: solid black 2px;
width:100%;
font-size:30px
}

input[type="button"]:hover{
background-color:#D3D3D3;
cursor:pointer;
}
input[type="text"]
{
background-color:white;
border: solid black 2px;
width:100%;
font-size:30px
}
</style>
</head>
<body>
<div class = title >Calculator</div>
<table border="10" style="width:100%;">
<tr>
<td colspan="3"><input type="text" id="result"/></td>
</tr>
<tr>
<td><input type="button" value="1" onclick="dis('1')"/> </td>
<td><input type="button" value="2" onclick="dis('2')"/> </td>
<td><input type="button" value="3" onclick="dis('3')"/> </td>
<td><input type="button" value="/" onclick="dis('&nbsp;/&nbsp;')"/> </td>
<td><input type="button" value="c" onclick="clr()"/> </td>
</tr>
<tr>
<td><input type="button" value="4" onclick="dis('4')"/> </td>
<td><input type="button" value="5" onclick="dis('5')"/> </td>
<td><input type="button" value="6" onclick="dis('6')"/> </td>
<td><input type="button" value="(" onclick="dis('(')"/> </td>
<td><input type="button" value=")" onclick="dis(')')"/> </td>
</td>
</tr>
<tr>
<td><input type="button" value="7" onclick="dis('7')"/> </td>
<td><input type="button" value="8" onclick="dis('8')"/> </td>
<td><input type="button" value="9" onclick="dis('9')"/> </td>
<td><input type="button" value="+" onclick="dis('&nbsp;+&nbsp;')"/> </td>
<td><input type="button" value="-" onclick="dis('&nbsp;-&nbsp;')"/>
</tr>
<tr>
<td><input type="button" value="." onclick="dis('.')"/> </td>
<td><input type="button" value="0" onclick="dis('0')"/> </td>
<td><input type="button" value="=" onclick="solve()"/> </td>
<td><input type="button" value="×" onclick="dis('&nbsp*&nbsp;')"/> </td>
<td><input type="button" value="π" onclick="dis('3.1415926535')"></td>
</tr>
</table>
</body>
</html>`

How to sync UI with changes in virtual cart?

I am learning some front end design patterns, and I keep reading about how in a shopping cart example, you want to have a virtual shopping cart, and then have the UI listen for changes to it, and then reflect it on the page. But I have not found good examples of exactly how to “listen for changes and reflect it” particularly where I’m essentially syncing changes in multiple places.

Below I took a stab at a most rudimentary system. The code WORKS (fiddle here), however, it seems wildly brittle (especially since reality could be far more complex than this with a lot more things to have to match to find the right cart row. The changePriceInUI and removeFromUI functions, for example, rely on matchers, because I’ve learned that item.row can only reference 1 jQuery object in either Cart page or Total page. That’s why the code that’s commented out, if used, would only affect the UI on cart-body in the Total page. But the code that’s commented out is what makes most sense to me in terms of most accurately working with items in a cart and syncing changes.

For example, I can imagine item being a Class where each time the price is changed, there’s a setter function that updates the UI (but again, item.row is only 1 row). But I guess not? Would love to hear how shopping carts are built to sync up changes. Other learning resources welcome!

cart = []
cart_body = $(".cart-body")

function addItem(name, price) {
  item = {}
  item.name = name
  item.price = price  
  item.row = $("<tr class='item-row' data-name='"+name+"' data-price='"+price+"'><td class='name'>" + name + "</td><td class='price'>" + price + "</td></tr>")
  cart.push(item)
  addToUI(item.row)
}

function addToUI(item_row) {
  cart_body.append(item_row)
}

function removeItem(name,price) {
  var length = cart.length
    for (var i = 0; i < length; i++ ) {
    if (cart[i].name == name && cart[i].price == price) { 
      item_whose_row_to_remove = cart[i]
      cart.splice(i,1)
      break
    }
  }
  removeFromUI(item_whose_row_to_remove)
}

function removeFromUI(item) {
  // item.row.remove()
  cart_body.find(".item-row[data-name='"+item.name+"'][data-price='"+item.price+"']").remove()
}

function changeItemPrice(name,new_price) {
  var length = cart.length
    for (var i = 0; i < length; i++ ) {
    if (cart[i].name == name) { 
      old_price = cart[i].price
      cart[i].price = new_price
      item_whose_price_to_update = cart[i]
      break
    }
  }
  changePriceInUI(item_whose_price_to_update, old_price)
}

function changePriceInUI(item, old_price) {
  // item.row.find(".price").empty().append(item.price)
  cart_body.find(".item-row[data-name='"+item.name+"'][data-price='"+old_price+"']").find(".price").empty().append(item.price)
}


addItem("Ball", 1)
addItem("Stick",2)
removeItem("Ball",1)
changeItemPrice("Stick",3)

Why is my transition time not being applied?

I am pushing each raindrop into rainDropArray, then I thought to call a function within the rainDropInterval, hmm(), and Im getting the transformation, just not the timed transition.

var rainDropArray = []; 
var rainDrop;
var randomDrop;
var yourTankOverThere;
var a=0;    
var rainDropInterval = setInterval(function(){

randomDrop = Math.floor(Math.random()*1000);    
rainDrop = 
document.createElement('div');
document.body.appendChild(rainDrop);rainDrop.style='box- 
sizing:border-box;border:1px solid green;height:7px;width:7px;background- 
color:green;position:absolute;top:0px;left:'+randomDrop+'px;transition:transform 
10s';
rainDrop.setAttribute('id','drop'+a);
yourTankOverThere 
=document.querySelector("#drop"+a);rainDropArray.push(yourTankOverThere);


 hmm();  


 },100);    
 function hmm() 
 {rainDropArray[a].style.transform="matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,0,1000,0,1)";a++}

how to display the right movie informations in an overlay?

I’m looking for solutions to display the right movie information in my overlay.
I have a “popup window” that appears when i click on a movie and it is supposed to display movie’s informations in it but when I click on a movie, no matter which one it is, it only displays the last movie informations, what Should I do to fix it ?

const movieIntegration =() => {
    allMovies.map(movie=> {
        movieGallery.innerHTML += `<div class="imgContainer">
                                        <img src="${movie.img}" alt="${movie.name}">
                                                <div class="titleContainer">
                                                    <div class="movieTitle"> ${movie.name} </div>
                                                    <div class="seemore"> See more </div>
                                                </div>
                                    </div>`

        const seemore = document.querySelectorAll(".seemore")
        seemore.forEach(elm => {
            elm.addEventListener("click",() => {
                pageContainer.innerHTML += `<div class="popupContainer">
                                                <div class="popup">

                                                    ${movie.name}

                                                    <div id="likeButton">
                                                        <img src="img/like.png">
                                                    </div>

                                                    <div id="editButton">
                                                        <img src="img/edit.png">
                                                    </div>

                                                    <a href="submit.html">
                                                        <div id="addingButton">
                                                            <img src="img/add.png">
                                                        </div>
                                                    </a>
                                                </div>
                                            </div>`
                console.log(true)
            }, true)
        })
    })
    
}

Can a JavaScript loop, upon the second iteration, iterate from the result of the prior iteration?

I just joined Stack Overflow and this is my first post so please do not hesitate to let me know if I am doing anything wrong.

I was presented with a challenge to create a function that accepts a string and calls another given function which swaps indices until the string is returned backwards.

I have gotten as far as below:

//given function
function swap(str, first, last){
    str = str.split('');
    let firstIndex = str[first];    
    str[first] = str[last];
    str[last] = firstIndex;
    str = str.join("").toString()
    return str;
}

//my function
let word = "Hello"
function reverseSwap(str) {
  let result = ""
  for (let i = 0; i < str.length/2; i++) {
  result += swap(str, i, str.length -1 - i);
  }
  return result;
}
console.log(reverseSwap(word))

This however returns “oellHHlleoHello”, because each iteration swaps indices from the original string then concatenates. Is it possible, upon the second iteration, to have the loop iterate from the result of the prior iteration so the following occurs?:

result of first iteration: swap(word, 0, 4) which returns “oellH”
second iteration uses “oellH” instead of “Hello” to swap(1, 3) which returns “olleH”
Then, swap(2,2) which doesn’t change anything.

createReactionCollector is not a function error

Error:

        const collector = message.createReactionCollector({ filter, time: 15000 });
                                  ^

TypeError: message.createReactionCollector is not a function

Code:


module.exports = {
    name: 'rules',
    description: 'Server Rules',
    permission: "ADMINISTRATOR",
    /**
     * 
     * @param {MessageReaction} message 
     */
    execute(message) {
        const rulemebed = new MessageEmbed()
        .setColor('#ffc7fe')
        .setTitle('Server Rules')
        .setDescription('Please click the check mark ✅ to verfiy that you read the rules and gain access to other channels')
        .setFooter('Abusing loop holes will result in fair punishment ')
        .addFields(
            {name: '#1', value:'...',},
        );
        

        message.channel.send({ embeds: [rulemebed] }).then((sentMessage) => {
            sentMessage.react("✅");
        });
        const filter = (reaction, user) => {
            return reaction.emoji.name === '✅' && user.id === message.author.id;
        };
        
        const collector = message.createReactionCollector({ filter, time: 15000 });
        
        collector.on('collect', async(reaction, user) => {
            const role = await message.guild.roles.fetch("916861450281156678");
            
            message.guild.members.fetch(user.id).then(member => {
                member.roles.add(role);
                member.roles.remove("916929706182459392");
            });
        });
    }
}

The code works just fine until I added the reaction collector starting at line 25 The goal is to make it when someone clicks the emoji “✅” they will be givin a role. I’m using discord.js v13 and node.js v16.13.0

Implement the form on JS + AJAX

I can’t solve the problem. I need to create a form, when I click on the buttons from the file on the server reads the name and surname and displays them in the HTML page (data will be taken from the input). The second form allows you to edit information about you and save it.

let form = document.forms.user

form.submit.addEventListener("click", sendRequest)

function sendRequest(e) {
    e.preventDefault() 
    let formData = new FormData(form) 
    let request = new XMLHttpRequest() 

    request.open()
    request.onreadystatechange = function() {
        if (request.readyState == 4 && request.status == 200) {
             document.getElementById("output").INNERHTML = request.responsText
        }
    }

    request.send(formData)
}

I do not know how to implement all the above functionality. Help me please 🙂

How to import Firebase v9 Auth Error object (JS SDK)

Here’s where I need it:

      try {
        await updatePassword(user, password);
      } catch (e) {
        if (e instanceof AuthError) {
          setErrorMessage(e.message);
        }
      }

The reason it’s failing is because AuthError is just an interface exported from the ‘firebase/auth’ module not an actual Error subclass.

onsubmit is still submitting the form even if it returns false?

I have a form in HTML page. It includes:

<form action="result.html" method="get" onsubmit="return ValidationEvent()">

So even the ValidationEvent() returns false I can render the result.html. Below is the definition of the function:

// Below Function Executes On Form Submit

function validation() {

// Storing Field Values In Variables
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var contact = document.getElementById("contact").value;
// Regular Expression For Email
var emailReg = /^([w-.]+@([w-]+.)+[w-]{2,4})?$/;

// Conditions
if (name != '' && email != '' && contact != '') {
    if (emailReg.test(email)==true) {
        //  if (email.match(emailReg)) 
        if (document.getElementById("male").checked || document.getElementById("female").checked) {
            if (contact.length == 10) {
                alert("All type of validation has done on OnSubmit event.");
                console.log("All type of validation has done on OnSubmit event.")
                return true;
            } 
            else {
                alert("The Contact No. must be at least 10 digit long!");
                console.log("The Contact No. must be at least 10 digit long!");
                return false;
            }
        } 
        else {
            alert("You must select gender.....!");
            return false;
        }
    } 
    else {
        alert("Invalid Email Address...!!!");
        return false;
    }
} 
else {
    alert("All fields are required.....!");
    return false;
}

}

How can prevent the form to be submitted.