Why are HTML tables I’m loading into TinyMCE corrupting themselves when all other content renders correctly?

I have a platform that allows individuals to create their own online forms. The structure of these forms are stored in a JSON format, and then this data is used to render the form to the end-user. When building a form, you have the option to use TinyMCE for textareas, to allow rich-text content.

Incomplete forms can be saved for future completion. In this instance, the JSON is again saved, but this time including an additional userData array which contains all the data that has been entered so far. When a user continues, this JSON is then reloaded, and fields are automatically populated with their existing data.

This all works fine. It also works fine for TinyMCE instances – except when it involves a table.

It’s somewhat hard to explain, so I have provided an example.

The following is a rendered form and I have inserted some data

Picture of generated form

The code used to generate (the empty) form is:

var formData = ‘[{“type”:”text”,”required”:false,”label”:”A Text Field”,”className”:”form-control”,”name”:”text-1640899516795″,”subtype”:”text”},{“type”:”textarea”,”subtype”:”tinymce”,”required”:false,”label”:”TinyMCE Text Area”,”className”:”form-control”,”name”:”textarea-1640638516810″}]’;

The TinyMCE element will show the following source code for the table I have entered:

<table style="border-collapse: collapse; width: 100%;" border="1">
<tbody>
<tr>
<td style="width: 31.5117%;">header 1</td>
<td style="width: 31.5117%;">header 2</td>
<td style="width: 31.5138%;">header 3</td>
</tr>
<tr>
<td style="width: 31.5117%;">Entry 1</td>
<td style="width: 31.5117%;">Entry 2</td>
<td style="width: 31.5138%;">Entry 3</td>
</tr>
</tbody>
</table>

Now, if I save the form and reload, the form is populated with my data – except, as you will see, the table is messed up.

Corrupted table

The source displayed by TinyMCE is:

<table style="border-collapse: collapse; width: 100%;" border="1">
<tbody>
<tr>
<td style="width: 31.5117%;">header 1</td>
<td>&nbsp;</td>
<td>Entry 31.5138%;"&gt;Entry 3</td>
</tr>
</tbody>
</table>

The JSON being used to generate the form looks like this:

var formData = ‘[{“type”:”text”,”required”:false,”label”:”A
Text
Field”,”className”:”form-control”,”name”:”text-1640899516795″,”subtype”:”text”,”userData”:[“whatever”]},{“type”:”textarea”,”subtype”:”tinymce”,”required”:false,”label”:”TinyMCE
Text
Area”,”className”:”form-control”,”name”:”textarea-1640638516810″,”userData”:[“<table
style=”border-collapse: collapse; width: 100%;”
border=”1″>rnrnrn<td style=”width:
31.5117%;”>header 1rn<td style=”width: 31.5117%;”>header 2rn<td style=”width: 31.5138%;”>header 3rnrnrn<td style=”width: 31.5117%;”>Entry 1rn<td style=”width:
31.5117%;”>Entry 2rn<td style=”width: 31.5138%;”>Entry 3rnrnrn”]}]’;

I’m working on the basis that something in the above is breaking the rendering, but I can’t work out what. Equally, this issue only seems to occur when using tables. You can go wild with formatting in TinyMCE and it will always render correctly after saving – unless you use a table.

I appreciate I’m using a lot of custom rendering here, but can anyone help me narrow down where things are going wrong?

How to make a button only visible under certain condition(the condition increase everytime one clicks the button?)

I am making a Javascript game, where I would like a button (class = “build”) to only be visible under certain conditions, and the condition would increase every time after one click the button.

To increase the number by 1, click the “gather” button. To make it more effective, click the “build” button to automatically increase the number by 0.1 per second. But I would like the “build” button to be only visible after the number reached 10. The “build” button would decrease the current number by 50% when one clicks it so that it would become invisible after being clicked.

The second time, the “build” button would only be visible when the number reached 12. Click it, the number decreases 50%, the “build” button disappears. The third time the button would become visible when the number reached 14 (so it’s +2 every time”), click it, the number decreases 50%, the “build” button disappears and it goes on and on.

Is there any way for this to work? I have some basic code down. Thanks!


let btn1 = document.querySelector(".btn1");
let btn2 = document.querySelector(".btn2");
let num = document.getElementById("num");
let increment = 0;

function toGather(){
num.innerHTML++;
}

btn1.addEventListener("click",toGather)

function toBuild() {
increment+=.1

if (increment == .1){
  setInterval(() => {
    num.innerHTML =parseFloat(parseInt((parseFloat(num.innerHTML)+.05+increment)*10)/10);
    
    
  }, 1000)} else num.innerHTML =parseFloat(parseInt((parseFloat(num.innerHTML)+.05+increment)*10)/10);
}

btn2.addEventListener("click",toBuild);

<span id="num">0</span>
<button class="btn1">Gather</button>
<button class="btn2">Build</button>

Javascript to Search In Multiple Tables in same page with multiple search bars

I found this previous thread, which is EXACTLY what I need but for some reason I can’t get it to work.
Javascript to Search In Multiple Tables in same page

I copied the code exactly from this jsfiddle (http://jsfiddle.net/690713m4/1/) to an entirely new page just to eliminate any bonehead errors I was potentially making and it still will not work like it does in the jsfiddle

Here is the code :

    <html>
    <script sec="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script srt="https://code.jquery.com/jquery-3.3.1.js"></script>
    <body><div class="input-group">
    <input class="form-control" id="search" type="text">
</div>

<table id="table" class="table paginated table-hover no-wrap">  
  <tr><td>PHP</td></tr>
  <tr><td>C#</td></tr>
  <tr><td>Javascript</td></tr>
  <tr><td>Jquery</td></tr>
  <tr><td>SQL</td></tr>
</table>
<br><br>

<div class="input-group">
    <input class="form-control" id="search2" type="text">
</div>
<table id="table2" class="table paginated table-hover no-wrap">  
  <tr><td>Bootstrap</td></tr>
  <tr><td>Java</td></tr>
  <tr><td>C++</td></tr>
  <tr><td>Pyton</td></tr>
  
<script>var $rows = $('#table tbody tr');
$('#search').keyup(function() {
  var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();

  $rows.show().filter(function() {
    var text = $(this).text().replace(/s+/g, ' ').toLowerCase();
    return !~text.indexOf(val);
  }).hide();
});

var $rows2 = $('#table2 tbody tr');
$('#search2').keyup(function() {
  var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();

  $rows2.show().filter(function() {
    var text = $(this).text().replace(/s+/g, ' ').toLowerCase();
    return !~text.indexOf(val);
  }).hide();
});</script>
</table>
</body>
</html>

Do I need to use await for async actions in react components?

I made this store:

export class CommentStore {
  comments = []

  constructor() {
    makeAutoObservable(this, {}, { autoBind: true });
  }

  async loadPostComments(postId: number): Promise<void> {
    const res = await API.loadPostComments(postId);
    runInAction(() => {
      this.comments = res;
    });
  }

  async sendComment(postId: number, comment: Comment): Promise<void> {
    try {
      await API.sendComment(postId, comment);
      await this.loadPostComments(postId);
      return true;
    } catch (err) {
      console.log('oops');
    }
  }
}

Do i need use await in react components? For example:

useEffect(() => {
      (async function () {
        await loadPostComments(postId);
      })();
    }, [loadPostComments, postId]);

But this also works fine:

useEffect(() => {
  loadPostComments(postId);
}, [loadPostComments, postId]);

Same for sendComment onClick:

onClick={()=>{sendComment(postId, comment)}}
onClick={async ()=>{await sendComment(postId, comment)}}

So, is it necessary to use await in this situations?

Text animation in contact form – HTML/CSS

I have the following code:

/* Contact Form */

input[type=text],
[type=email],
select,
textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #555;
  margin-top: 6px;
  margin-bottom: 16px;
  resize: vertical;
}

input[type=submit] {
  background-color: #0563bb;
  color: white;
  padding: 12px 20px;
  border: none;
  cursor: pointer;
}

input[type="text"]:focus,
input[type="email"]:focus,
#subject:focus {
  background: var(--bgFormElsFocus);
  transform: scale(1.02);
  transition: transform 0.2s ease-in-out;
}

input[type=submit]:hover {
  opacity: 0.9;
}

.contactform {
  position: relative;
  border-radius: 50px;
  background-color: #f2f2f2;
  padding: 5px;
  z-index: 2;
  display: block;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: auto;
  margin-top: 1%;
  width: 100%;
  animation-name: gradient;
  animation-duration: 3s;
  animation-iteration-count: infinite;
}

.contactform:hover {
  animation-name: gradient;
  animation-duration: 15s;
  animation-iteration-count: infinite;
}

.column {
  float: center;
  width: 50%;
  margin-top: 6px;
  padding: 20px;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

.row:after {
  content: "";
  display: table;
  clear: both;
}

@media screen and (max-width: 600px) {
  .column,
  input[type=submit] {
    width: auto;
    margin-top: 0;
  }
}

.shakingErr {
  border-color: red;
  animation: shake 0.82s forwards;
}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}
<section id="contact">
  <div class="container" data-aos="fade-up">
    <div class="contactform">
      <div style="text-align:center">
        <div class="section-title">
          <h2><br/>Get In Touch</h2>
        </div>
        <p>Feel Free To Reach Out To Me Through This Form! </p>
      </div>
      <div class="row">
        <div class="column">
          <form name="myform" action="https://formspree.io/f/xr123gjbqpq" id="my-form" method="POST" novalidate>
            <label for="firstname">First Name</label>
            <input type="text" id="first name" name="firstname" placeholder="Your First Name.." required>
            <label for="lastname">Last Name</label>
            <input type="text" id="lastname" name="lastname" placeholder="Your Last Name.." required>
            <label for="email">Email:</label>
            <input type="email" id="email" name="email" placeholder="Your Email.." required>
            <label for="subject">Subject</label>
            <textarea id="subject" name="subject" placeholder="Lets Collaborate.." style="height:170px" required></textarea>
            <input type="submit" value="Submit">
          </form>
        </div>
      </div>
    </div>
  </div>
</section>

I would like a text animation on the input fields. For example, I would like my expected output to be like this:

https://watch.screencastify.com/v/3mlMie2rx0UzhdymHYCR

As you can see, I would like the text such as “First Name” to be inside the input field, and when the user clicks the input field, the text should animate and be at the top. How can I achieve this task? Any suggestions?

How can I animate an accelerating a DOM element with JavaScript?

I am making an application where I need a object to move from point a to point b starting out fast but then slowing down. I want to do this with pure vanilla js and no libraries whatsoever. This is my current code for animating something at a constant speed and I was wondering if it was possible to modify it or something.

let player = document.querySelector('.player');
var id = setInterval(frame, 1);
let counter = 0;
function frame() {
    if (counter == 50) {
        clearInterval(id);
                counter = 0;
        return;
    } else {
        player.style.top = player.offsetTop - 2 + 'px';
        counter++
    }
}

Ajax json doesnt show any instances

that even if i connected json data to ajax, it doesnt show me any results.

def get_json_categories(request):
    query_get = request.GET
    if query_get:
        query_get = query_get['q']
        categories = EcommerceProductCategory.objects.filter(name__contains=query_get).order_by('name')
    else:
        categories = EcommerceProductCategory.objects.order_by('name')

    data = {}
    data['results'] = []
    for category in categories:
        data_to_return = {}
        data_to_return['id'] = category.id
        data_to_return['name'] = category.name
        data['results'].append(data_to_return)

    return JsonResponse(data)

And i urled that to ecommerce/get_json_categories

and in the Django html

<div class="mt-2">
                <hr>
                <div class="form-group">
                    <select class="form-control w-30" name="category_select" id="category_select" aria-describedby="category_select" required></select>
                </div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
    $('#category_select').select2({
        placeholder: 'Wybierz kategorię',
        ajax: {
            url: 'http://127.0.0.1:8000/ecommerce/get_json_categories',
            dataType: 'json',
            data: function (params) {
                return {
                    q: params.term,
                    page: params.name
                };
            },
        }
    });
</script>

But it shows me “No results could be found” but that site (/ecommerce/get_json_categories) is full of json data.

How to group an array of objects in mongodb

im new to mongodb and Im having some trouble to group an array from a document like this:

_id: ObjectId('5d7afa2609d6ed000dffe1de')
email: "email@email.com"
transactions: [
    {
        "date": "2020-06-10T00:00:00.000+00:00",
        "shares": 100,
        "price": 20,
        "type": "buy",
        "equity_id": "petr4"
    },
    {
        "date": "2020-07-10T00:00:00.000+00:00",
        "shares": 200,
        "price": 10,
        "type": "sell",
        "equity_id": "petr4"
    },
    {
        "date": "2020-06-10T00:00:00.000+00:00",
        "shares": 250,
        "price": 30,
        "type": "buy",
        "equity_id": "vale3"
    }, ...
]

I would like to group these transactions by date and obtain an document like this:

_id: ObjectId('5d7afa2609d6ed000dffe1de')
email: "email@email.com"
transactionsByDay: {
    "2020-06-10": [
        {
            "shares": 100,
            "price": 20,
            "type": "buy",
            "equity_id": "petr4"
        },
        {
            "shares": 250,
            "price": 30,
            "type": "buy",
            "equity_id": "petr4"
        }
    ],
    "2020-07-10": [
        {
            "shares": 200,
            "price": 10,
            "type": "sell",
            "equity_id": "petr4"
        }
    ], ...
}

I tried an aggregation using a group operator but the result didn’t came as expected. Can someone give me a help to solve this?

Vis.js How to show only children/descendents of selected node?

If not posible with vis.js, I could do the entire thing on something else. But this functionality is crucial. So, show everything if nothing selected; show only children (with the “from” arrow) of some node if that node is selected. Or to select the node in some list, or type it somewhere.
https://codepen.io/andre-fr-silva/pen/ZEBPpqK

var container = document.getElementById("mynetwork");
var data = {
  nodes: nodes,
  edges: edges,
};

Why doesn’t my useEffect go into an infinite loop when modifying it’s dependency?

Code

PrizeHistory.js

...

const PrizeHistory = () =>  {
  const [history, setHistory] = useState([]);

  useEffect(() => {

    async function getHistory () {
      try {
        let result = await sqliteInterface.getAllPrizes(db, prizeTable);
        result == null ? console.log("res is null") : setHistory(result);
        console.log("result" + result);
        console.log("history" + history);
      } catch (err) {
        console.log(err);
      }
    }

    getHistory();
  }, [history])

  return (
    <View style={styles.body}>
      <Text style={styles.text}>Prize History</Text>
    </View>
  );
}

getAllPrizes

getAllPrizes(db, tableName) {
    return new Promise((resolve, reject) => {
      db.transaction((tx) => {
        tx.executeSql(
          `SELECT * FROM ${tableName};`, 
          [],
          (tx, res) => {
            let len = res.rows.length;
            let results = [];  

            if(len > 0) {
              for(i = 0; i < res.rows.length; i++) {
                results.push(res.rows.item(i));
              }
            } 
            console.log("resolving promise now");
            resolve(JSON.stringify(results));
          },
          (error) => {
            reject(Error(`SQLite getAllPrizes: failed to get '*' from ${tableName}: ` + error));
          }
        );
      }); 
    });
  }

The goal

When the page is mounted, set the history state to the data in the database. I initially tried this:

  useEffect(() => {

    async function getHistory () {
      try {
        let result = await sqliteInterface.getAllPrizes(db, prizeTable);
        result == null ? console.log("res is null") : setHistory(result);
        console.log("result" + result);
        console.log("history" + history);
      } catch (err) {
        console.log(err);
      }
    }

    getHistory();
  }, [])

but it never set my history variable correctly. I just got an empty array (which is what I inistially set the history state to). I expected the history variable to be equal to the result variable in the history console.log(), but it’s not.

So I changed the useEffect() to this:

  useEffect(() => {

    async function getHistory () {
      try {
        let result = await sqliteInterface.getAllPrizes(db, prizeTable);
        result == null ? console.log("res is null") : setHistory(result);
        console.log("result" + result);
        console.log("history" + history);
      } catch (err) {
        console.log(err);
      }
    }

    getHistory();
  }, [history])

This code changes the history variable correctly, but I expected it to go into an infinite loop… but it didn’t? Here’s my logic

  1. useEffect() has [history] as dependency
  2. onMount, history is set to default value of []
  3. useEffect() sees history is set and begins running
  4. useEffect() resets history
  5. useEffect() should start again because it reset the history variable itself
  6. Repeat 3-5 infinitely…

But it does not repeat infinitely…

My Questions

  1. Why is useEffect() not running infinitely when [history] is set as its dependency
  2. Why is useEffect() not setting my history variable correctly on mount when it has [] as it’s dependency.

how to show youtube video in an html page with value received via json

I would like your help.
I have to insert a youtube video whose url is received via json; in particular with

document.getElementById("idframe").innerHTML=myJson.Items[4].value;

I get https://youtu.be/ILmvKC-H1l0

So far everything ok. To insert the youtube video in an html page I was following this tutorial.

I just can’t get what I want. I get a gray box with the words: It may have been moved, changed, or deleted.
Can you kindly help me?

<html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style></style>
    </head>
    <body>

    <div>
<div class="video"> <iframe id="idframe" width="420" height="345" src="myFunction()"> </iframe> </div> <br>

    <br>

    <script>

    function myFunction() {
      var xmlhttp = new XMLHttpRequest();
    var url = "https://vnwcn9gt89.execute-api.us-east-2.amazonaws.com/book"; 
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
       var myJson = JSON.parse(this.responseText);
       document.getElementById("idframe").innerHTML = myJson.Items[4].value;
      }
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
    }

    </script>


    </body>
    </html> 

Add interactive menu which moves a dot when user scroll down the page

I’m trying to create a small animated menu which would be positioned on the top of my one-page website. Page is organised as a book, so it would have chapters like introduction etc. as you scroll from top to bottom. My small menu would have one line and along this line would be names of chapters.There would also be a dot, and the dot would move along this line, and depending on which chapter have you positioned your browser, dot would move along and position itself accordingly. Also, if you click on the specific chapter on this menu, browser would automatically jump there, as well as the little dot. Problem is, I’m new to CSS/HTML/Javascript and I have difficulties in doing this. So far I managed to create a dot and names of chapters but I have issues in positioning them. For some reason, line I created won’t show but circle will.
So, to sum it up:

  1. create a horizontal line in the middle
  2. position dot at beginning of the line (Intro chapter)
  3. position names of chapters under the line on some regular intervals
  4. add logic which will follow which chapter is shown in the browser and move little dot accordingly
  5. add links to jump to specific part of the page when user clicks on specific chapter name in the menu (this part I know how to do)
.section{
    background:black;
    width: %100;
    /* center a div insie another div*/
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
    height: 200px;
}

.circle {
    width: 5px;;
    height: 5px;
    margin: 10px;
    background: white;
    border-radius: 50%;
}

ul {
  display: flex;
}

li {
  color: white;
  transform: rotate(65deg);
  transform: translate (-30px,-30px);
  list-style-type: none;
}

.line {
  height 10px;
  width: 100%;
  transform: translate (50%,0);
}

.list {
  transform: translate(50%,50px);
}
<div class="section">
  <div class="list">
  <ul>
    <li>Intro</li>
    <li>Part 1</li>
    <li>Part 2</li>
  </ul>
  </div>
   <div class="circle"></div>
  <div class="line"></div>
</div>

How to import google form response into specific cells in an existing template

I am trying to create a user friendly way to fill out a questionnaire using google forms but import the responses into specific cells within an existing spreadsheet.

So, each child has their own spreadsheet that compiles their data. I have a template that lists each question and has a cell for a numeric response.

  • Currently, I have the spreadsheet set up where the parents select their numeric response from a scale: 0, 2, 4, 8, 10 using a dropdown per question. But there are over 100 questions, which is both time consuming on their end and would also give them access to additional data in “hidden sheets” from the clinicians, even if the sheets are protected from editing.

So, I am wanting to create a form that is connected to the client’s spreadsheet that the parents can fill out and their responses will be imported into the respective cells that match up with each question on the data sheet.

  • For example, if a parent selects a rating of “2” on the google form in response to a question of the level of independence of their child for question 1, I’d want their response of “2” to be reflected in the child’s respective data sheet in cell T16 within the template I have created.
  • Then the numeric response to question 2 would be reflected in cell T17.

However, the responses would not be continuous throughout the entire column (T). The responses would need to be in cells T16:T31, T38:T64, T71:T97, and continues on in blocks.

It would also need to import the child’s name and the submission date in respective cells as well.

An additional parameter: Each child has their own spreadsheet, so the link to the parent form would somehow need to be automatically connected to each child separately whenever a new copy of the data sheet was created. So that way an infinite number of children have their own dataset.

I hope that makes sense! Any help would be much appreciated! Please let me know if additional clarification is needed!

Next+Nextauth Get user’s session as a ServerSideProp

I’m trying to implement Facebook login and session by using nextauth in a next.js project.
once the user is authenticated I want to retrieve the session and pass it to my component as a server-side prop to avoid unnecessary load time

My […nextauth.js] file

import NextAuth from "next-auth"
import FacebookProvider from "next-auth/providers/facebook";

export default NextAuth({
  // Configure one or more authentication providers
  secret: process.env.SECRET,
  providers: [
    FacebookProvider({
      clientId: process.env.FACEBOOK_CLIENT_ID,
      clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
    }),
    // ...add more providers here
  ],
})

I’ve double-checked my env variables FACEBOOK_CLIENT_ID FACEBOOK_CLIENT_SECRET NEXTAUTH_URL and SECRET

my _app.js file

import "../styles/globals.css";
import { SessionProvider } from "next-auth/react"

export default function App({
  Component, 
  pageProps: { session, ...pageProps }
}) {
  return (
    <SessionProvider session={session}>
      <Component {...pageProps} />
    </SessionProvider>
  )
}

In my index.js component, I’m handling the login

import { useSession, signIn, signOut,getSession } from "next-auth/react"
import Head from 'next/head'
import Header from '../components/Header'
import Login from '../components/Login'

export default function Home({session}) {
  if (!session) return <Login></Login>
  return (
    <div >
      <Head>
        <title>Facebook</title>
      </Head>
      <h1>Signed in as {session.user.email}</h1>
      <Header/>
      <main>
        {/* Sidebar */}
         {/* feed */}
         {/* widgets */}
      </main>
    </div>
  )
  
}
export async function getServerSideProps(context) {
  const session = await getSession(context)
  return {
    props: { session }
  }
}

In mi Login.js component I’m just using the signIn method provided by next auth

The thing is:

  1. When I try to retrieve the session by using getServerSideProps it doesn’t provide me a session and I cannot get to the home page, BUT if I instead use the custom hook inside the component, I get a session and everything works fine, but I think it is better if I pass the session as a serverside prop
const session = await getSession() //this works but is client-side
  • Is there something I’m missing out on? I’ve read the docs and followed the steps but it doesn’t quite work

  • besides Is there a difference between next-auth/react and next-auth/client?
    I have “next-auth”: “^4.0.0-beta.7” package installed in this proyect

If anyone could shed some light over this topic and on why I cant get the session as a serverSide prop I would be thankful.