Automatically submit a value on click to a form using Javascript/Java in a Django form

I am working on a web app using Django/Python/Javascript/Java. The focal point is a map of the USA. A user should be able to click on a region and the value of that region should automatically query a database and return certain information. Currently, my code produces a const called regionName and the value of regionName is passed automatically as input to the search bar; however, from here a user needs to manually click the ‘search’ button to submit the form and query the database. As below:


  onRegionClick: function(event, code){
            console.log('event', event, 'code', code);
            const regionName = map.getRegionName(code);
            console.log('regionName', regionName);
            $("#selection").val(regionName);
  
        },

      });

What I am trying to do with the code is to automatically submit the value of regionName after it is passed to the search bar. Efforts thus far have been similar to the code below.

$(“#selection”) – the form

$(“#q”) – the name of the button

 $("#selection").on('change', function(){
                if ($("#selection").val() === regionName ) {
                  $("#q").click();
                }
              }); 

This is not producing any errors, but it’s not producing any results either.

I’ve tried various substitutes along similar lines such as:

.on(‘input’.. instead of ‘change’
.submit() instead of .click()

I’ve also have an .autocomplete() method I’m using. I’m not sure if this is causing a conflict.


<script type="text/javascript">
            $(function () {
              var states = [
                {% for states in states %}

                " {{states.state}} ",

                {% endfor %}

              ];

              $("#selection").autocomplete({
                  source: states
              }); 

            });

          </script>

TypeError: Cannot read properties of undefined (reading ‘length’) in DataTable

I want to populate a DataTable using the jQuery ajax but I keep bumping into a TypeError: Cannot read properties of undefined (reading ‘length’).

For context, I am using the Hope UI datatable template for this.

Here’s the HTML code for the table:

<div class="table-responsive">
    <table id="boards_table" class="table table-striped" data-toggle="data-table">
        <thead>
            <tr>
                <th>Model</th>
                <th>Serial</th>
                <th>Revision</th>
                <th>Owner</th>
                <th>Date Owned</th>
                <th>Updates</th>
                <th>Notes</th>
                <th>Date Added</th>
                <th>Status</th>
                <th>History</th>
            </tr>
        </thead>

        <tfoot>
            <tr>
                <th>Model</th>
                <th>Serial Number</th>
                <th>Revision</th>
                <th>Owner</th>
                <th>Date Owned</th>
                <th>Updates</th>
                <th>Notes</th>
                <th>Date Added</th>
                <th>Status</th>
                <th>History</th>
            </tr>
        </tfoot>
    </table>
</div>

This is the script I use for the Ajax call:

$(document).ready(function() {
    var table = window.DataTable = $('#boards_table').DataTable({
        "order": [],
        "bootstrap": true,
        "bAutoWidth": true,
        "responsive": true,
        "processing": true,
        "serverSide": true,
        "aLengthMenu": [
            [25, 50, 75],
            [25, 50, 75]
        ],
        "pageLength": 25,
        "ajax": {
            url: "boards-ajax.php",
            type: "POST",

            "data": {
                GetBoards: "Yes",
            },

            error: function(xhr, textStatus, errorThrown) {

                var error = textStatus;
                var details = errorThrown;
                console.log(xhr.responseText);
                console.log("Status=" + xhr.status + "nStatusText=" + xhr.statusText + "nError=" + error + "&Detail=" + details)

            }
        },

        "dom": 'Bfrtip',
        "buttons": [{
            extend: 'excelHtml5',
            className: 'btn btn-link btn-soft-light',
            exportOptions: {
                columns: [2, 3, 4],
            }
        }],
        "initComplete": function(settings, json) {
            table.buttons().container().appendTo($('#boards_table_wrapper .col-sm-6:eq(0)'));
        },
    });
   
    $("#global_search").on('keyup', function() {
        table
            .search(this.value)
            .draw();
    });
});

And this is the PHP script the gets the data from the database:

if (isset($_POST['GetBoards'])) {

    if ($InventoryCon->connect_errno) {

        header('HTTP/1.1 503 Service Unavailable');
        exit();

    } else {

        $Query = "Select *    From boards     Where IsDeleted=0;";
        $AllRecords = array();
        $Result = mysqli_query($InventoryCon, $Query);

        if (!mysqli_query($InventoryCon, $Query)) {

            header('HTTP/1.1 500 Internal Server Error');
            throw new ErrorException($InventoryCon->error, 500);
            exit();

        } else {

            while ($Row = mysqli_fetch_assoc($Result)) {
                $RowArray = array();
                $RowArray[] = $Row['ModelName'];
                $RowArray[] = $Row['SerialNumber'];
                $RowArray[] = $Row['RevisionNumber'];
                $RowArray[] = 'Owner';
                $RowArray[] = $Row['DateOwned'];
                $RowArray[] = $Row['Updates'];

                // Notes icon
                $RowArray[] = 'Note Column';


                $RowArray[] = $Row['DateAdded'];

                //Status button
                $RowArray[] = 'Status Column';


                // History button
                $RowArray[] = 'History Column';

                $AllRecords[] = $RowArray;
            }
            $output = array(
                "draw" => 25,
                "recordsTotal" => mysqli_num_rows($Result),
                "recordsFiltered" => 25,
                "data" => $AllRecords
            );
            
                echo json_encode($output );
    
        }

        mysqli_close($InventoryCon);
    }
}

The Ajax call returns 200 OK and if I add a success function, I can see that the data is also returned as it should.

I scoured the internet to see what solutions other people found, but none did the trick.

‘Refused to set unsafe header “cookie”‘ durante requisição AJAX [closed]

Olá!
Estou criando um forms tipo ‘hidden’ dentro da minha página, e usando AJAX para enviar as respostas ao meu script Google, que alimenta um Sheets com essas respostas.


Link da página:
https://mcczdmjzbk7rtly9nsqx690fd25y.pub.sfmc-content.com/5jfgjvgskj2?qs=9668f36134cc0e1ee13aa77b9332e5b392103a9f7c562abae9b517d752603a0b2d07c69ed5273475a671496c1b77abcefd27b435212c1559d3568825826915fdf1a6fe64666c9d20c478fcae3c249994ad0c05434ec04b866e1f79cb81c9ebf206d830a696fb7e64829699de91f93beb79370f049ef1a11dfc22bd774e162980&utm_source=&utm_medium=crm&utm_term=&utm_content=&utm_campaign=

Google Script link:
https://script.google.com/home/projects/1lEMTZz1a0nu-HwO7qXHlBixNIKxh54xA19RRQY59_FWlre2hqOjV5DO_/edit


O botão ‘Finalizar’ inicia as requisições AJAX.
%%=v(@email_address)=%%, por exemplo, é uma variável recebida pela página via Salesforce, com notação própria.

<form id='respostas'>
                  
  <input type="hidden" name="email_buyer" value="%%=v(@email_address)=%%">
  <input type="hidden" name="nota" value="%%=v(@nota)=%%"> 
  <input type="hidden" name="buyer_name" value="%%=v(@first_name)=%%">
    
  <div class="button-wrapper" style=" display: flex; justify-content: center;">
   
    <button style="background-color:#588e8f"type="submit" class="mt-25" id="submit-form">
    Finalizar
    </button>

  </div>
              
</form> 

As requisições são enviadas ao script Google usando ‘GET’


              $("form#respostas").submit(function(event) {
                 var $form = $('form#respostas');
                 request = $.ajax({
                        url: "https://script.google.com/a/macros/mobly.com.br/s/AKfycbyxmoJMS2UerY_sqiTuSLX5a7EO8G_NNb7Jb4aS4eo8DHCKVDG_YMqliIIrIFhrlXf-/exec?callback=?",
                        type: "get",
                        crossDomain: true,
                        datatype: "jsonp",
                        headers: {
                          "accept": "*/*",
                          "cookie": "",
                          'Access-Control-Allow-Origin': '*',
                        },
                        data: $form.serialize(),
                        success: () => {
                          console.log('Sucesso.');
                        }
                       });
                       request.done(function (response, textStatus, jqXHR){
                        console.log(JSON.stringify(response));
                        alert("Obrigado pela resposta! Você já pode sair desta página");
                    });
                    request.fail(function (response, textStatus, jqXHR){
                      console.log(response,'######',textStatus,'#######',jqXHR)
                      alert("fail");
                    });
                    event.preventDefault();
                  //return false;
                      });

Clicando no botão ‘Finalizar’, recebo o alerta de falha.
Inspecionando a página encontrei o erro Refused to set unsafe header “cookie”.
Alguém sabe dizer o que está errado no código, ou o que poderia estar faltando?
Nunca vi esse erro antes.
Obrigado!!

Google sheets script order not executing properly

I have a spreadsheet that loads a customer’s saved checkout sheet. When the function is called it loads a snapshot of the customer’s checkout sheet the last time it was saved. After the snapshot is loaded there are 3 fields that need to be altered to set the proper day and time of the new checkout.

I’ve tried writing the code where these three fields are at the end of the function, where they are a function by themselves that gets called at the end of the original function, and have tried using a Utilities.sleep(), all which do not work. What ends up happening for all these scenarios is the three cells will change to their expected values for a split second, and then revert to the values that were loaded from a customer’s saved sheet.

I don’t understand who this is happening, as these 3 cells are being altered only after the previous code has completed. Help please!

  function loadSnapshot(){

//Gets checkout sheet ID from Customer's profile  
  try {
  let artistName = SpreadsheetApp.getActiveSpreadsheet().getRange('Signature Sheet!F6:F6').getValue()
  let customerCheckoutSheetID = DriveApp
  .searchFiles(`title contains "${artistName} + Saved Checkout Sheet"`).next().getId();
  
  
  let customerSheetLR = SpreadsheetApp.openById(customerCheckoutSheetID).getSheets()[0].getLastRow()
  let customerSheetLC = SpreadsheetApp.openById(customerCheckoutSheetID).getSheets()[0].getLastColumn()

  let customersSheetValues = SpreadsheetApp.openById(customerCheckoutSheetID).getSheets()[0].getSheetValues(1,1,customerSheetLR,customerSheetLC)

  let mainSheetActiveRange = SpreadsheetApp.openById('xxx').getSheets()[0].getRange('Signature Sheet!A1:H41')
  let mainSpreadsheetValues = SpreadsheetApp.openById('xxx')
  .getSheets()[0].setActiveRange(mainSheetActiveRange).setValues(customersSheetValues)
  
  headerFields()
  
  }
catch(error){
  SpreadsheetApp.getUi().alert('No Saved Snapshot')
 }
}

function headerFields(){
//Header Formulas
  var spreadsheet = SpreadsheetApp.getActive()
  let checkoutTime = spreadsheet.getRange('Signature Sheet!F9:F9').setFormula('=now()')
  let hoursUsed = spreadsheet.getRange('Signature Sheet!F10:F10').setValue('')
  let timeFormula = spreadsheet.getRange('Signature Sheet!F11:F11').setFormula('=NOW()+TIME(F10,0,0)')

}

How to change the Boostrap 4 Accordion card header color when active

I am trying to change the header color to my $primary color and the text color to white when the tab is active. When the tab is not opened I want it to be my $unactive color for the tab and the font color to be my $primary color. Any help would be great. I am using scss to make it so the site doesnt look like every other bootstrap site.

//app.scss 
// override all variables first
$primary: #fff;
$tertiary: goldenrod;
$secondary: #003e7a;
$unactiveTab: #ebf2fa;
$theme-color: (
"tertiary": $tertiary,
        "unactiveTab": #ebf2fa,
);
.jumbotron {
  background: url('https://www.wctc.edu/_site-images/it-web-and-software-developer-bl.jpg') no-repeat;
  background-size: cover;
  height:460px;
  width: 100%;
  font-weight: bold;
  text-align: center;
  }
.nav-pills{
  background-color: $secondary;
  color: $primary;
}
.card-header{
  color: $secondary;
}
.nav-pills.active{
  background-color: $secondary;

}
.card-header .btn[aria-expanded=true] {
  color: $primary;
  background-color: $secondary;
}
.card-header.btn[aria-expanded=false] {
  color: $secondary;
  background-color: $unactiveTab;
}
.card.show {
  background-color: $secondary;
  color: $primary;
}
//index.html
<div class="container">
<div id="accordion">
    <div class="card">
        <div class="card-header bg-secondary" id="headingOne">
            <h5 class="mb-0">
                <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
                   Contact us
                </button>
            </h5>
        </div>

        <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion">
            <div class="card-body">
            <p> <strong>Questions?</strong> We'd love to help! Connect with our Outreach team by filling out our online form or by email at <a href = "mailto:[email protected]" style="color: blue; text-decoration: underline">[email protected]</a>.</p>
            </div>
        </div>
    </div>
    <div class="card">
        <div class="card-header" id="headingTwo">
            <h5 class="mb-0">
                <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
                   Potential Careers
                </button>
            </h5>
        </div>
        <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordion">
            <div class="card-body">
                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
            </div>
        </div>
    </div>
    <div class="card">
        <div class="card-header" id="headingThree">
            <h5 class="mb-0">
                <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
                    High School Eligibility
                </button>
            </h5>
        </div>
        <div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordion">
            <div class="card-body">
                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
            </div>
        </div>
    </div>
    <div class="card">
        <div class="card-header" id="headingFour">
            <h5 class="mb-0">
                <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
                    Career Salaries
                </button>
            </h5>
        </div>
        <div id="collapseFour" class="collapse" aria-labelledby="headingFour" data-parent="#accordion">
            <div class="card-body">
                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
            </div>
        </div>
    </div>
    <div class="card">
        <div class="card-header" id="headingFive">
            <h5 class="mb-0">
                <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
                   Financial Aid
                </button>
            </h5>
        </div>
        <div id="collapseFive" class="collapse" aria-labelledby="headingFive" data-parent="#accordion">
            <div class="card-body">
                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
            </div>
        </div>
    </div>
    <div class="card">
        <div class="card-header" id="headingSix">
            <h5 class="mb-0">
                <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
                   Which Degree is For Me?
                </button>
            </h5>
        </div>
        <div id="collapseSix" class="collapse" aria-labelledby="headingSix" data-parent="#accordion">
            <div class="card-body">
                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
            </div>
        </div>
    </div>
</div>
</div>

Retrieve array of objects from local storage

Trying to make to-do list but I have difficulties with local storage. First i don’t understand why does local storage returns [object Object] instead of actual text. Secondly at some point local storage becomes empty and then begins to fill in from the beginning. That’s so confusing for me

function addTask() {
    let addTaskButton = document.getElementById('add-task-button')
    let list = document.getElementById('task-list');
    let li = document.createElement('li');
    let checkbox = document.createElement('input');
    let taskText = document.createElement('span');
    let delButton = document.createElement('button');
    let btnText = document.createTextNode('Delete task');

    checkbox.type = 'checkbox';
    checkbox.className = 'checkbox';
    taskText.innerText =  document.getElementById('input-task').value;
    taskText.className = 'task';
    delButton.className = 'delete-btn';
    delButton.addEventListener('click', deleteTask)
    delButton.addEventListener('click', updateStorage)
    addTaskButton.addEventListener('click', updateStorage);

    delButton.appendChild(btnText);
    li.appendChild(checkbox);
    li.appendChild(taskText);
    li.appendChild(delButton);
    list.appendChild(li);

    document.getElementById('input-task').value = '';


    taskList.push({
        text: taskText.innerText,
        checked: false
    });
}

let taskList = [];

function updateStorage() {
    localStorage.setItem('tasks', JSON.stringify(taskList));
    console.log(taskList)
}

function deleteTask () {
    this.parentNode.remove();
}

document.getElementById('add-task-button').addEventListener('click', addTask);

function loadList() {
    document.querySelector('ul').innerHTML = JSON.parse(localStorage.getItem('tasks')) || [];
}

window.addEventListener('load', loadList);

zoom/pan two deck.gl containers simultaneously?

I have two deck.gl containers that zoom/pan separately. I want to be able to zoom/pan both of them when I zoom/pan on either. Right now the containers are in two instantiations of deck.gl, but I’m not sure how I can create multiple containers in one new Deck.gl({})

Looking at the documentation, I see how this is possible with React, but I don’t want to use React.

Any thoughts?
Here is my code, and it’s also in a Plunkr– where you’ll find the geojson.

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            width: 100vw;
            height: 100vh;
            margin: 0;
            padding: 0;
            background: #dad6d0;
        }

        #ca1 {
            height: 100vh;
            width: 50vw;
            position: absolute;
            left: 0;
        }

        #ca2 {
            height: 100vh;
            width: 50vw;
            position: absolute;
            left: 50vw;
        }
    </style>
</head>

<body>
    <div id='ca1'></div>
    <div id='ca2'></div>
    <script src='https://unpkg.com/deck.gl@latest/dist.min.js'></script>
    <script>
        const { DeckGL, GeoJsonLayer, MapController } = deck;

        const ca_state = new GeoJsonLayer({
            data: 'california.json',
            id: 'castate',
            opacity: 1,
            getLineWidth: 23,
            stroked: true,
            filled: true,
            getFillColor: f => [10, 67, 216],
            getLineColor: f => [25, 95, 190],
            pickable: false
        });

        const ca_state2 = new GeoJsonLayer({
            data: 'california.json',
            id: 'castate',
            opacity: 1,
            getLineWidth: 23,
            stroked: true,
            filled: true,
            getFillColor: f => [218, 207, 82],
            getLineColor: f => [25, 95, 190],
            pickable: false
        });

        class MyMapController extends MapController {
            handleEvent(event) {
                if (event.type === 'pan') {
                    // do something
                } else {
                    console.log('custom map controller')

                    super.handleEvent(event);
                }
            }
        }

        new DeckGL({
            mapStyle: '',
            initialViewState: {
                latitude: 37.337840681197655,
                longitude: -120.19909774948918,
                zoom: 5.5,
                maxZoom: 16,
                minZoom: 0,
                pitch: 0
            },
            controller: MyMapController,
            container: 'ca1',
            layers: [ca_state],
        });

        new DeckGL({
            mapStyle: '',
            initialViewState: {
                latitude: 37.337840681197655,
                longitude: -120.19909774948918,
                zoom: 5.5,
                maxZoom: 16,
                minZoom: 3,
                pitch: 0
            },
            controller: MyMapController,
            container: 'ca2',
            layers: [ca_state2],
        });
    </script>
</body>

</html>

How to open accordion open on hover

How to make accordin to open on hover?
I want the accordin open on hover and close when I move the cursor to another direction.
I want this because it has an arrow function that mean the arrow move up when open and down when it gets close.

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <title>Hello, world!</title>
  </head>
  <body>
    <div class="accordion" id="accordionExample">
  <div class="accordion-item">
    <h2 class="accordion-header" id="headingOne">
      <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
        Accordion Item #1
      </button>
    </h2>
    <div id="collapseOne" class="accordion-collapse collapse show" aria-labelledby="headingOne" data-bs-parent="#accordionExample">
      <div class="accordion-body">
        <strong>This is the first item's accordion body.</strong> It is shown by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
      </div>
    </div>
  </div>
  <div class="accordion-item">
    <h2 class="accordion-header" id="headingTwo">
      <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
        Accordion Item #2
      </button>
    </h2>
    <div id="collapseTwo" class="accordion-collapse collapse" aria-labelledby="headingTwo" data-bs-parent="#accordionExample">
      <div class="accordion-body">
        <strong>This is the second item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
      </div>
    </div>
  </div>
  <div class="accordion-item">
    <h2 class="accordion-header" id="headingThree">
      <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
        Accordion Item #3
      </button>
    </h2>
    <div id="collapseThree" class="accordion-collapse collapse" aria-labelledby="headingThree" data-bs-parent="#accordionExample">
      <div class="accordion-body">
        <strong>This is the third item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
      </div>
    </div>
  </div>
</div>

    <!-- Optional JavaScript; choose one of the two! -->

    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

    <!-- Option 2: Separate Popper and Bootstrap JS -->
    <!--
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
    -->
  </body>
</html>

How to make accordin to open on hover?
I want the accordin open on hover and close when I move the cursor to another direction.
I want this because it has an arrow function that mean the arrow move up when open and down when it gets close.

Polymorphic callback function not recognized

I am getting the error Uncaught (in promise) TypeError: modNums is not a function. I am following a guide and what I have below is roughly similar to what they did.

Is the issue coming from the fact that I am trying to call the callback inside of a fetch callback? How can I make the modNums function get called? Mind you modNums is just the name of the parameter and there are multiple function that are meant to be accepted for that function value (hence polymorphism).

function updatePageText (chapter, page, modNums) {
  fetch("../../assets/json_files/parsedPages.json")
    .then((Response) => Response.json())
    .then((data) => {
      modNums(chapter, page, data); 

_

updatePageText(chapterNum, pageNum, increasePage);

SWC with JavaScript: How to handle CSS imports and how to absolute imports?

TL;DR

  • How can you tell SWC to compile CSS files imported in React components?
  • How can you tell SWC to compile absolute imports in tests and in React components?

Context

We’re migrating from Babel to SWC. (I asked a question a little while ago. I’m improving on that question’s answer.)

We’re migrated the command from:

"test": "NODE_ENV=test riteway -r @babel/register 'src/**/*.test.js' | tap-nirvana",

to

"test": "SWC_NODE_PROJECT=./jsconfig.json riteway -r @swc-node/register src/**/*.test.js | tap-nirvana",

where the jsconfig.json looks like this:

{
  "compilerOptions": {
    "allowJs": true,
    "baseUrl": "./src",
    "jsx": "react-jsx"
  }
}

If we write try to compile a test for a self-contained component (no absolute imports, no CSS) it works:

import { describe } from 'riteway';
import render from 'riteway/render-component';

function HomePageComponent({ user: { email } }) {
  return <p>{email}</p>;
}

describe('home page component', async assert => {
  const user = { email: 'foo' };
  const $ = render(<HomePageComponent user={user} />);

  assert({
    given: 'a user',
    should: 'render its email',
    actual: $('p').text(),
    expected: user.email,
  });
});

The test compiles fine.

With Babel we had a .babelrc like this:

{
  "env": {
    "test": {
      "plugins": [
        [
          "module-resolver",
          {
            "root": [
              "."
            ],
            "alias": {
              "components": "./src/components",
              "config": "./src/config",
              "features": "./src/features",
              "hocs": "./src/hocs",
              "hooks": "./src/hooks",
              "pages": "./src/pages",
              "redux": "./src/redux",
              "styles": "./src/styles",
              "tests": "./src/tests",
              "utils": "./src/utils"
            }
          }
        ]
      ]
    }
  },
  "presets": [
    [
      "next/babel",
      {
        "ramda": {}
      }
    ]
  ],
  "plugins": [
    ["styled-components", { "ssr": true }]
  ]
}

Where the styles where taken care of by styled-components and the absolute imports where defined via the module-resolver plugin. (We switched away from styled-components to CSS modules, which is why we import from .module.css CSS files. Anyways …)

If we write the test how we wanted to write it with their actual imports like this:

import { describe } from 'riteway';
import render from 'riteway/render-component';
import { createPopulatedUserProfile } from 'user-profile/user-profile-factories';

import HomePageComponent from './home-page-component';

describe('home page component', async assert => {
  const user = createPopulatedUserProfile();
  const $ = render(<HomePageComponent user={user} />);

  assert({
    given: 'a user',
    should: 'render its email',
    actual: $('p').text(),
    expected: user.email,
  });
});

It fails with:

$ SWC_NODE_PROJECT=./jsconfig.json riteway -r @swc-node/register src/features/home/home-page-component.test.js | tap-nirvana
/Users/janhesters/dev/my-project/src/features/home/home.module.css:1
(function (exports, require, module, __filename, __dirname) { .container {
                                                              ^

SyntaxError: Unexpected token '.'

when we leave in the CSS import in home-page-component.js, or with:

$ SWC_NODE_PROJECT=./jsconfig.json riteway -r @swc-node/register src/features/home/home-page-component.test.js | tap-nirvana
node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module 'user-profile/user-profile-factories'
Require stack:
- /Users/janhesters/dev/my-project/src/features/home/home-page-component.test.js
- /Users/janhesters/dev/my-project/node_modules/riteway/bin/riteway

respectively, when we get rid of the CSS import.

How can we help SWC understand CSS (or mock CSS modules) and how can we help it understand absolute imports?

We already set the baseUrl in jsconfig.json

Leave server command? [closed]

I am Owner of a Discord Bot. I want to have like a leave server command, where I can put the ID and then the bot leaves the server. For example ,leaveserver 1234567 and then the bot leaves the server. How can I do that?

trying to grab a value from an array in javascript

im trying to make it so it only shows specific sizes for the array i have, this is the array

const products = [{
    name: "14K bracelet",
    id: "1",
    description: "Beautfull 14K gold Bracelet",
    price: 100,
    size: [1, 2, 3, 4]
    
}

and this is how im trying to grab the values from it

                    <Dropdown.Item className="dropdown-item" href="#/action-1">{products.size[0]}</Dropdown.Item>

but im getting this error

TypeError: Cannot read properties of undefined (reading '0')

Can’t access redux actions from props when working with react router

I’m pretty new to react and redux and I have been having a problem accessing my redux actions from the props when used in conjunction with react router. I have tried lots of configurations for formatting but no matter what I try the props only have the react router functions i.e. history, match and location. I am using connected-react-router but it does not seems to be doing anything. I have been able to access the redux actions from my nav menu components so I don’t think anything is wrong there.

Here is a sample of the latest configuration I tried:

const mapStateToProps = (state) => {
    return { isSignedIn: state.auth.isSignedIn }
}

const ConnectedApp = connect(
    mapStateToProps,
    { signOut, signIn }
)(App);

ReactDOM.render(
    <Provider store={store}>
        <ConnectedRouter basename={baseUrl} history={history}>
            <ConnectedApp />
        </ConnectedRouter>
    </Provider>,
  rootElement);

and here is inside App:

class App extends Component {
    static displayName = App.name;


  render () {
    return (
        <Layout>
            <Route exact path='/' component={(props) =><Home {...props}/>} />
            <Route exact path='/LogInExisting' component={(props) => <LogInExisting {...props} />} />
            <Route exact path='/LogInCreate' component={(props) => <LogInCreate {...props} />} />
      </Layout>
    );
  }
}

I feel like I am missing something obvious but I really could use some help.

🍎”help.microsoft.com 🍎*877[947]7788*🍎

Microsoft is a major technology company that sells software, electronics and computers around the world. As one of the largest companies in the world, it isn’t surprising that its tech support department gets a lot of calls every day.
Microsoft prefers it when customers begin their support requests through the Microsoft website. Once on the “Contact Us” page, you will be presented with a menu of products and services
Microsoft Support Number help.microsoft.com talk to a person toll–free number The certified experts directly get in touch with you over the call, understand the issue and provide the best solution accordingly. They might narrate the steps to resolve the errors over the call or seek remote access to your system to perform the solution steps to get rid of the errors. Seeking Microsoft Helpline Number Support is the best way to fix Microsoft errors.
Please note, every software is prone to errors and glitches. Despite being a robust and advanced application, Microsoft may show errors. But this does not put a question mark to its proficiency and capabilities. Here are some of the most impeccable features of Microsoft.
https://stackoverflow.com/questions/70898043/help...