Populating an HTML table from an external XML (multiple Values)

I have come across a problem while fetching data from an external XML document with JS. I have been following the w3schools tutorial for AJAX XML so far, but I ran into something I couldn’t solve. I have a XML that looks like this:

THE XML

<root>
 <document-id>
    <author>Tom Riddle</autor>
    <title>abzy</title>
    <year>1995</year>
 </document-id>
 <document-id>
    <author>Tom Riddle</autor>
    <author>Albums Dumbledore</autor>
    <title>abzy</title>
 </document-id>
 <document-id>
    <author>Tom Riddle</autor>
    <year>1995</year>
 </document-id>
</root>

I want to access the Data in the above XML and generate a table with all the values. Something I ran into is that if I have for example multiple authors my request will only fetch one author’s for each TR element and if there are two it will simply move it down into the next. Is there a way that my code can take all the authors from one document-id and put them into the same td?

The HTML and JS Code

<body>
    <header>
        <h1>Reading Data from XML Files</h1>
    </header>
    <main>

        <button type="button" onclick="loadDoc()">Get my CD collection</button>

        <table id="demo">

        </table>

    </main>   
    <script>
       function loadDoc() {
          const xhttp = new XMLHttpRequest();
          xhttp.onload = function() {
            myFunction(this);
          }
          xhttp.open("GET", "books.xml");
          xhttp.send();
        }
        function myFunction(xml) {
          const xmlDoc = xml.responseXML;
          const x = xmlDoc.getElementsByTagName("document-id");
          console.log(x)
          let table="<tr><th>Author</th><th>Title</th><th>Year</th></tr>"; 
          for (let i = 0; i <x.length; i++) { 
            table += "<tr><td>" +
            x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue == undefined)?"": x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue ) +
            "</td><td>" +
            x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue == undefined)?"": x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue ) +
            "</td><td>" +
            x[i].getElementsByTagName("year")[0].childNodes[0].nodeValue == undefined)?"": x[i].getElementsByTagName("year")[0].childNodes[0].nodeValue ) +
            "</tr>";
          }
          document.getElementById("demo").innerHTML = table;
        }
    </script>
</body>

How to mock Request global.Header before executing test cases in jestjs?

So Im unit testing some functions which contains Headers and I’ve managed to mock the global.Headers by running following code before executing the test.

beforeAll(() => {
  const append = jest.fn();
  // set test `Headers`
  global.Headers = () => ({
    append: append,
  });
});

I’m however trying to mock this within the setup.js, so I don’t require to fire make similar beforeAll(()=>{} code for all my test files. I’m not to where I need to point the mock properly, below is what’ve done.

setup.js

jest.mock(global.Headers, () => {
  global.Headers = () => ({
    append: jest.fn(),
  });
});

Whats the point of top level await?

So the whole Top-level await thing is completely flying over my head. I don’t get it. How is top level wait any different than a top level promise? I am not being argumentative, I honestly think I am missing something here. I’ve been writing a parser that parses some JSON stuff which pertains to a UI (details about the parser are irrelevant so I will spare you from having to read them). I created a simple to read, comprehend & understand interface that is asynchronous. I wrote it in TypeScript (nightly v4.7.0) Node v17.6.0 & configured the project as an ESM module so that I knew I would have support for Top Level Awaits.

Using a Top Level await I executed the following asynchronous api method call.
await jsonFile
    .readData('./src/res/test-theme.json')
    .then((data) => {
        console.log('Printing JSON-Files Content:n%s', data.toString());
});


What I don’t understand, is why would you care about top level await, when you can just do the same thing w/o await, for example:
jsonFile
    .readData('./src/res/test-theme.json')
    .then((data) => {
        console.log('Printing JSON-Files Content:n%s', data.toString());
});


I know that I use promises all the time, and I pretty much never reach for async, or await, consequently; I am likely thinking with a one track promise based mind. To put this post in clear question format, where is the benefit in using a top level await over a top level promise?

ReactJS onChange only triggers in Firefox

I have a peculiar problem with ReactJS (latest version) where the input onChange event does not trigger at all in Chrome. Sample code are as follows:

function NewTodoComponent() {
    const [description, setDescription] = useState('');

    const submit = async(e) => {
        await createNewTodo(description);
        setDescription('');
    }

    const _changeHandler = (e) => {
        setDescription(e.target.value)
    }

    return (
        <div>
            <div>
                <label for="description">Description</label>
                <input type="text" name="description" value={description} onChange={_changeHandler} />
                <button onClick={submit}>Submit</button>
            </div>
        </div>
    );
}

This exact same code works in Firefox. Not sure why it’s behaving like this.

Removing margin/padding CSS/HTML

I can’t seem to get rid of the slight margin/padding that is on my entire site (currently working on a codecademy assignment).

I’ve looked through the entire document for any margins that I made have acccidentally added or padding settings, but I can’t seem to find it anywhere. What is causing the white space on the sides of the website?

Here is the CSS and HTML for my website:

/* Universal Styles */

html {
  font-family: "Roboto", sans-serif;
  font-size: 16px;
}

body {
  border-style: border-box;
}

ul {
  list-style-type: none;
}

a {
  text-decoration: none;
  color: #4A4A4A;
}

.content {
  padding: 0;
  margin: 0;
}

header .content {
  display: flex;
  margin: 0 0;
  justify-content: space-between;
  align-items: center;
  height: 85px;
}

.desktop {
}

.desktop ul {
  display: flex;
}

.desktop li a {
  margin: auto 25px;
  display: flex;
  align-items: center;
}

.desktop img {
  height: 20px;
  width: 20px;
}

.mobile {
  display: none;
}

#sign-up-section {
  background-image: url("banner-landingpage.jpg");

  color: white;
}

#sign-up-section .content.center {
  background-color: #9DC20A;
  margin-top: 170px;
  margin-bottom: 170px;
  margin-left: 100px;

}

#sign-up-section .cursive {
  font-family: Damion, curisve;
  font-weight: 50;
  font-size: 3em;
}

#sign-up-section .striking {
  color: white;
  font-size: 50px;
  font-family: 'Rubik-Regular', sans-serif;
  line-height: 1.4;
}
<!DOCTYPE html>
<html>
<head>
  <link href="https://fonts.googleapis.com/css?family=Damion" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Rubik" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,600,700" rel="stylesheet">
  <link rel="stylesheet" href="./resources/css/style.css">
  <meta charset="UTF-8">
</head>
<body>
  <!-- Header -->
  <header>
    <div class="content">
      <a href="index.html" class="desktop logo">Fotomatic</a>
      <nav class="desktop">
        <ul>
          <li><a href="#">Product detail</a></li>
          <li><a href="#">About us</a></li>
          <li><a href="https://www.instagram.com/">Follow us <img class="icon" src="./resources/images/instagram.png"></a></li>
        </ul>
      </nav>
      <nav class="mobile">
        <ul>
          <li><a href="#"><img src="./resources/images/ic-logo.svg"></a></li>
          <li><a href="#"><img src="./resources/images/ic-product-detail.svg"></a></li>
          <li><a href="#"><img src="./resources/images/ic-about-us.svg"></a></li>
          <li><a href="#" class="button">Join us</a></li>
        </ul>
      </nav>
    </div>
  </header>

  <!-- Main Content -->
  <div class="main-content">

    <!-- Sign Up Section -->
    <div id="sign-up-section" class="banner">
      <div id="sign-up-cta">
        <div class="content center">
          <div class="header">
            <h2 class="cursive">Instant</h2>
            <h1 class="striking">FORMAT CAMERA</h1>
          </div>
          <div class="email">
            <span>
              Email us to request a demo and be in our waiting list for the <strong>Febuary 2017</strong> release!
            </span>
            <div class="button">Join the waiting list</div>
          </div>
        </div>
      </div>
    </div>

    <!-- Features Section -->
    <div id="features-section">
      <div class="feature">
        <div class="center">
          <div class="image-container">
            <img src="./resources/images/feature-1.png" />
          </div>
          <div class="./resources/content">
            <h2>Advanced, automatic, instant</h2>
            <h3>Shutter speed, apperture and flash output adjust automatically</h3>
          </div>
        </div>
      </div>
      <div class="feature">
        <div class="center">
          <div class="image-container">
            <img src="./resources/images/feature-2.png" />
          </div>
          <div class="content">
            <h2>Beautifully crafted inside-out</h2>
            <h3>From the paint outside to the tiny screw inside, Fotomatic is crafted with love and 20-year of expertise</h3>
          </div>
        </div>
      </div>
    </div>

    <!-- Filters Section -->
    <div id="filters-section">
      <div class="content center">
        <h2>Over 20+ filters to choose from</h2>
        <h3>Feed your creativity with 20 different filter designed by our eclectic in-house photographers!</h3>
      </div>
      <div class="images-container">
        <div class="image-container">
          <img src="./resources/images/filter-1.png" />
        </div>
        <div class="image-container">
          <img src="./resources/images/filter-2.png" />
        </div>
        <div class="image-container">
          <img src="./resources/images/filter-3.png" />
        </div>
        <div class="image-container extra">
          <img src="./resources/images/filter-4.png" />
        </div>
      </div>
    </div>

    <!-- Quotes Section
    <div id="quotes-section">
      <div class="content center">
        <span class="quote">“It’s truly something that could create a brand new photography Renaissance”</span>
        <img class="quote-citation" src="./resources/images/photography-logo.png" />
      </div>
    </div>

    <!-- Footer -->
    <footer>
      <div class="content">
        <span class="copyright">© 2016  Fotomatic, All Rights Reserved</span>
        <span class="location">Designed in NYC</span>
      </div>
    </footer>

  </div>
</body>
</html>

How Can we remove the HTML from string and return an object from it

I have a string which looks like

var str = <strong>Result completed.</strong> This has been done by user steve at 2am

Now, from this string I would like to remove the strong as well as , I am trying divide this string in two parts,

{
  title: "Result completed.",
  desc: "This has been done by user steve at 2am"
}

So , is there any way I can get this result using javascript

Thanks

JSON object with nested key type

Write a function to iterate through a json and print all the values in that json recursively. That json can have objects, arrays or array of objects or even nested arrays and objects
eg:

[[[[{a:{b:{c:1}}}]]],1,3]
{a:1,b:{c:2},d:[1,2]}

How to stop angular service worker from caching facebook pixel?

I have enabled facebook pixel into my angular webApp. But it only works on if i hard refresh. After that the request gets triggered via service worker and not getting registered in the facebook pixel extension.
I have tried including the links into the dataGroups.
I have also tried the ngsw-bypass=true query param
enter image description here

Everything works fine if i remove the service worker from my app.

ngsw-config.json
{
  "index": "/index.html",
  "dataGroups": [
  {
      "name": "api",
      "urls": ["https://connect.facebook.net/en_US/fbevents.js","https://connect.facebook.net/signals/config/**"],
      "cacheConfig": {
          "maxSize": 0,
          "maxAge": "0u",
          "strategy": "freshness"
      }
  }
  ],
  "assetGroups": [
    {
      "name": "assets",
      "installMode": "lazy",
      "updateMode": "prefetch",
      "resources": {
        "files": [
          "/assets/**",
          "/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"
        ]
      }
    }
  ]
}
load() {

      if (!this.loadOk) {

        (function (f: any, b, e, v, n, t, s) {
            if (f.fbq) return; n = f.fbq = function () {
                n.callMethod ?
                    n.callMethod.apply(n, arguments) : n.queue.push(arguments)
            }; if (!f._fbq) f._fbq = n;
            n.push = n; n.loaded = !0; n.version = '2.0'; n.queue = []; t = b.createElement(e); t.async = !0;
            t.src = v; s = b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t, s)
        })(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js?ngsw-bypass=true');
        // (window as any).fbq.disablePushState = true; //not recommended, but can be done
        (window as any).fbq('init', '1117176809040790');
 
        (window as any).fbq('track', 'PageView');
        this.loadOk = true;
        console.log('Facebook pixel init run!')
      }
      else {
        (window as any).fbq('track', 'PageView');
        console.log('Facebook PageView event fired!')
      }


  }

How to send a message to the iframe whose src has been changed

I am working on an html page which hosts a iframe and will change depending upon situation. The iframe src change is easily accomplished but sending message to that iframe (through iframe.contentWindow.postMessage) isn’t happening. I did some test run and saw that message being displayed on previous iframe.

After that I thought of using asynchronus approach (tries async/await and promise also) thinking my problem has to be because of that but the problem still persisted.

I am working with vanilla js and below is simplified snippet of codes.

Main index page

<!DOCTYPE html>
<html lang="en">
<body>
   <iframe id="bodyChange" src="pubMode.html" frameborder="0"></iframe>
   <script src="../script/popup.js"></script>
</body>
</html>

Now, below are html pages which have to be in iframe.

pubMode.html

<!DOCTYPE html>
<html lang="en">
<body>
    <button id="settingBtn">Setting</button>
    <button id="privMode">Private Mode</button>

    <div id="container"></div>
   <script src="../script/frame.js"></script>
</body>
</html>

setting.html

<!DOCTYPE html>
<html lang="en">

<body>
    <div id="settingPage"></div>

    <script src="../script/setting.js"></script>
</body>

</html>

privMode.html

<!DOCTYPE html>
<html lang="en">

<body>
    <button id="settingBtn">Setting</button>
    <button id="pubMode">Public Mode</button>

    <div id="container"></div>

    <script src="../script/frame.js"></script>
</body>

</html>

Js script.

frame.js

var frame = {
init: function(){
    //msg sender
    document.addEventListener('click', (event) => {
        var message = JSON.stringify({
            id: event.target.id
        });
        window.parent.postMessage(message, '*');
    });

    //msg reciever
    window.addEventListener('message', function (e) {
        document.getElementById('container').innerHTML = e.data;
    });
   
}}

popup.js

class popup{
  constructor(){
    window.addEventListener('message', (e) => {
            let data = JSON.parse(e.data);
            let myPromise = new Promise((resolve, error) => {
                let frameObj = document.getElementById('bodyChange');
                frameObj.src = this.iframeMap[data.id];

                resolve(frameObj);
            }); 
           
            myPromise.then(frameObj => {
                console.log(frameObj.src);
                frameObj.contentWindow.postMessage(response, '*');
            });
           }
         });
       }
    }

   var obj = new popup();

Error: Same values are appearing as options in the select. How can I remove duplicate values? [duplicate]

I have these data in which the cat will be the options of the select. However, as you can see in the sample data, there are 2 products with the same cat which is the S-XL. The problem here is that there will be 2 S-XL that show up as the options.

It shows up like this:

enter image description here

This is the data:

const products = [
  {
    prodName: "Tumbler",
    cat: "ML",
    price: 1.5,
    size: "500",
    colorMap: { Black: 20, Pink: 10, Green: 5 },
    id: "aRLMZkiSU7T0lcsPCSsV"
  },
  {
    prodName: "Shirt",
    cat: "S-XL",
    price: 2.0,
    size: "L",
    colorMap: { Blue: 10, Black: 10 },
    id: "uTHIR6OQFRuqP9Drft0e"
  },
  {
    prodName: "Shirt2",
    cat: "S-XL",
    price: 1.0,
    size: "M",
    colorMap: { Blue: 10, Black: 10 },
    id: "uTHIR6OQFRuqP9Drft0e"
  },
  {
    size: "200",
    cat: "CM",
    price: 2.0,
    colorMap: { Green: 50, Red: 19, Black: 20 },
    prodName: "Notebook",
    id: "y9ECyZBKp2OBekmWym4M"
  }
];

How do I prevent or remove these duplicates?

Codesandbox link: https://codesandbox.io/s/react-hook-form-wizard-form-from-reddit-with-data-changed-the-autocomplete-with-select-cd1e6u?file=/src/fieldArray.js:995-3536

const FieldArray = ({ control, register, setValue, getValues }) => {
  
  console.log(fields, "fields");

  const selectedCategory = fields.map((object) => object.category);
  console.log(selectedCategory, "selectedCategory");

  const filtered = products.filter((d) => d.cat === `${selectedCategory}`);
  console.log(filtered, "filter");

  const sizes = fields.map((object) => object.size);
  console.log(sizes, "size");

  return (
    <div>
      <ul>
        {fields.map((item, index) => {
          return (
            <li key={item.id}>
              <FormControl>
                <Controller
                  control={control}
                  name={`order.${index}.category`}
                  rules={{ required: "Please make a selection." }}
                  render={({ field, fieldState }) => (
                    <Select {...field}>
                      {products.map((option, i) => (
                        <MenuItem value={option.cat} key={i}>
                          {option.cat}
                        </MenuItem>
                      ))}
                    </Select>
                  )}
                />
              </FormControl>

              <FormControl>
                <Controller
                  control={control}
                  name={`order.${index}.size`}
                  rules={{ required: "Please make a selection." }}
                  render={({ field, fieldState }) => (
                    <Select {...field}>
                      {filtered.map((option, i) => (
                        <MenuItem value={option.size} key={i}>
                          {option.size}
                        </MenuItem>
                      ))}
                    </Select>
                  )}
                />
              </FormControl>
            </li>
          );
        })}
      </ul> 
    </div>
  );
};

export default FieldArray;

React Native: Base64 Image Array String not rendering in FlatList

I need to render a FlatList with Image Items in my RN App, but it looks like, I missed something out.
I’m fetching blob data and parse it with Buffer to a String from my API and push it to my Array. I use that Array to render that FlatList

export function HomeScreen() {
const imagesList: any = [];
useEffect(() => {
    loadData();
  }, []);
const loadData = async() =>{
await callAPI().then(res => {
//blob base64 is from type jpeg
imagesList.push({imageURI: "data:image/jpeg;base64,"+Buffer.from(
                res.image1,
              ).toString('ascii')})

}

return (
<View style={[styles.imageSlider, {width, height}]}>
            <FlatList
              data={imagesList}
              renderItem={({item, index}) => (
                <>
                  {console.log('item: ', item)}
                  <Image
                    key={index}
                    source={{uri: item.imageURI}}
                    style={{
                      height,
                      width,
                      resizeMode: 'cover',
                      maxHeight: 500,
                      maxWidth: 500,
                    }}
                  />
                </>
              )}
            />
</View>

)
}

Could anyone tell me my problem? I’m not an expert in RN
Thanks!

javascript addEventListener will run more than once after several clicking

Click button will trigger setup function and add change event to input file, after choosing file , it will upload. The question is that it will run multiple times based on uploading times.
I tried to reset the input file value after uploading , and still it will run twice in second times.
How to fix this problem, I don’t want to refresh page, and also I want it only run one time every click.

html code below

<input onclick='setup()' value='btn' type='button' class='btn btn-info'>
<form id='formid' method='POST' enctype='multipart/form-data'>
     <input accept='image/*' id='fileid' type='file' name='my_file' onsubmit='return false' />
     <input  type='submit' value='Submit' />
</form>

js code below

function setup(key) {
    document.getElementById('fileid').click();
    document.getElementById('fileid').addEventListener('change', submitForm);
    function submitForm() {
        var data = new FormData();
        data.append('my_file', $('#fileid').prop('files')[0]);
        $.ajax({
        url: 'ImageUpload.php',
        type: 'POST',               
        processData: false,
        contentType: false,
        data: data,
        success: function(data) {},
        error: function (error) {}
            });
        }
}

Is there any way to crop videos in JavaScript with a crop box, without using React or Vue?

I was trying to crop videos with cropper.js, but from what I understand that it is impossible and only works for photos. I’ve looked everywhere for resources to do such, but I couldn’t find anything. If you don’t know what I am talking about I would like something like this https://codesandbox.io/s/react-easy-crop-for-videos-lfhme but uses JavaScript instead of React. The reason I don’t want to switch to a frontend framework is because I am using Django for my backend, and am not comfortable with switching to APIs, and using React or Vue, since I am really far into my project. I also want to avoid using a hybrid architecture if possible. If anyone knows of any libraries or repositories I can check out that might help me that would be much appreciated.

Just in case I can use videos in cropper.js here is my source code.

    // file-box is the id of the div element that will store our cropping file preview
    const filebox = document.getElementById('file-box')
        // crop-btn is the id of button that will trigger the event of change original file with cropped file.
    const crop_btn = document.getElementById('crop-btn')
    // id_file is the id of the input tag where we will upload the file
    const input = document.getElementById('id_file')

    // When user uploads the file this event will get triggered
    input.addEventListener('change', ()=>{
      // Getting file file object from the input variable
      const img_data = input.files[0]
      // createObjectURL() static method creates a DOMString containing a URL representing the object given in the parameter.
      // The new object URL represents the specified File object or Blob object.
      const url = URL.createObjectURL(img_data)

      // Creating a file tag inside filebox which will hold the cropping view file(uploaded file) to it using the url created before.
      filebox.innerHTML = `<img src="${url}" id="file" style="width:100%;">`
      // Storing that cropping view file in a variable
      const file = document.getElementById('file')

      // Displaying the file box
      document.getElementById('file-box').style.display = 'block'
      // Displaying the Crop buttton
      document.getElementById('crop-btn').style.display = 'block'
      // Hiding the Post button
      document.getElementById('confirm-btn').style.display = 'none'

      // Creating a croper object with the cropping view file
      // The new Cropper() method will do all the magic and diplay the cropping view and adding cropping functionality on the website
      // For more settings, check out their official documentation at https://github.com/fengyuanchen/cropperjs
      const cropper = new Cropper(file, {
      autoCropArea: 1,
      aspectRatio: 1/1,
      viewMode: 1,
      scalable: false,
      zoomable: false,
      movable: false,
      minCropBoxWidth: 200,
      minCropBoxHeight: 200,
      })

      // When crop button is clicked this event will get triggered
      crop_btn.addEventListener('click', ()=>{
        // This method coverts the selected cropped file on the cropper canvas into a blob object
        cropper.getCroppedCanvas().toBlob((blob)=>{

          // Gets the original file data
          let fileInputElement = document.getElementById('id_file');
          // Make a new cropped file file using that blob object, file_data.name will make the new file name same as original file
          let file = new File([blob], img_data.name,{type:"file/*", lastModified:new Date().getTime()});
          // Create a new container
          let container = new DataTransfer();
          // Add the cropped file file to the container
          container.items.add(file);
          // Replace the original file file with the new cropped file file
          fileInputElement.files = container.files;

          // Hide the cropper box
          document.getElementById('file-box').style.display = 'none'
          // Hide the crop button
          document.getElementById('crop-btn').style.display = 'none'
          // Display the Post button
          document.getElementById('confirm-btn').style.display = 'block'

          });
        });
    });

php export to excel column formatting

I am using php library for exporting MySQL data into Excel.one of the columns having 12 digits does not show the 12 digit number(because of excel),every time I have to format cell and select number to view the full 12 digit number.How can I do this programmatically while writing excel? Your help will be highly appreciated.