how to change html script tag to jsx code?

Having trouble converting this to jsx, i know the tag itself in html represents jsx but when i add it to a new file thats a .js it just reads my code as text? it just displays my code as text on the webpage
(this code works on an html page, its an input box where a user would input an email for a newsletter)

<html>
<body>
   ...styling code elements
   ...styling code elements

<button  class="join" id = "join"> join </button>
  
        <script>
            let email = document.getElementById("email")
            document.getElementById("join").onclick = () => {
                console.log(email.value)
                fetch("/sendemail?email=" + email.value, {
                    method: "POST"
                }).then((res) => {
                    // success
                    alert("success")
                }).catch((err) => {
                    // error 
                    alert(err)
                })
            }
        </script>
   </body>
</html>

How to make a button open a small window within the html page

So you know how extensions work in Google, right? You click a button and it opens this small window within the internal webpage. I know how to make a button open an external window, but how do I make it work similarly to an extension. Basically, I’d like to have an html page where I can click a button and it’ll open a small popup of another .html file within the first html page. So it would be this: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_popup but where it says “A Simple Popup!” it’s an .html page.

to block display: none; from a div after i press a div button

my english is not so good but i try my best to explain my problem and i try like 10 topics to find a solution but im cant figure..

i want after i press this div

 <div id="test" class="br3 mb3 ph3 pv2 ba b--black-10 flex justify-between items-center pointer hover-b--primary5">
 <div class="f5 flex items-center">Test1</div>

to block the display to show the content of this div

 <div id="modal" style="display: none; width: 370px; position: fixed; right: 2px; top: 0; z-index: 99; background-color: white; border-radius: 0px 0px 10px 10px; box-shadow: 0 4px 30px rgba(0, 0, 0, 0.25);">

Thanks and have a great day 🙂

jQuery Delete table rows that were dynamically added [duplicate]

I have a simple table that by default shows a single row, with an add button for users to add additional rows if required. I have a delete icon showing in the last column for users to delete a row if they made a mistake, however this only works for the first table row and doesn’t work for any rows the user has added themselves.

Here’s a sample of how this looks:

$(document).ready(function() {
  $("#addRow").click(function() {
    var markup = "<tr><td><input type="text" class="form-control" autocomplete="off" placeholder="Serial" name="serial"></td><td></td><td></td><td></td><td><span class="glyphicon glyphicon-trash"></span></td></tr>";
    $("#shipmentConsignment").append(markup);
  });

  // Find and remove selected table rows
  $("#deleteRow").click(function() {
    $(this).closest('tr').remove();
  });
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>


<table id="shipmentConsignment" class="table table-condensed table-striped table-bordered">
  <thead>
    <th class="text-center" scope="col" width="20%">Serial</th>
    <th class="text-center" scope="col" width="15%">ID</th>
    <th class="text-center" scope="col" width="15%">Code</th>
    <th class="text-center" scope="col" width="45%">Description</th>
    <th class="text-center" scope="col" width="5%"></th>
  </thead>
  <tbody>



    <tr>
      <td><input type="text" class="form-control" autocomplete="off" placeholder="Serial" name="serial"></td>
      <td></td>
      <td></td>
      <td></td>
      <td id="deleteRow"><span class="glyphicon glyphicon-trash"></span></td>
    </tr>


  </tbody>
</table>


<button type="button" name="addRow" value="addRow" id="addRow" class="btn btn-primary">Add Item</button>

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)

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.

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++}