check the radio button when click on the li using javascript

I have radio button

Html code:

<input type="radio" class="first" name="bright" checked>
<input type="radio" class="second" name="bright" >
<input type="radio" class="third" name="bright">
<input type="radio" class="four" name="bright">

And i have a nav bar

Html code

<ul class="nav">

<li class="st st1 active" data-cont="first">
<h2 class="inner">وزارة الاستثمار</h2>
</li>
<li class="st st2" data-cont="second">
<h2 class="inner">وزارة التجارة</h2>
</li>
<li class="st st3" data-cont="third">
<h2 class="inner">جهات حكومية اخرى</h2>
</li>
<li class="st st4" data-cont="four">
<h2 class="inner">مكتب هندسي</h2>
</li>
 </ul>

These 2 are conected with the data-cont that have the class of the radio button

I want when i click on the li the correct radio button be checked using javascript

I tried to make it using this code in JavaScript

let radio = document.querySelectorAll("input");
let radioArray = Array.from(radio);
let tabs = document.querySelectorAll(".nav li");
let tabsArray = Array.from(tabs);


tabsArray.forEach((ele) => {
    ele.addEventListener("click", function (e) {
        tabsArray.forEach((ele) => {
            ele.classList.remove("active");
        });
        e.currentTarget.classList.add("active");
       document.querySelector(e.currentTarget.dataset.cont).checked = true;
    });
});

I try to remove the active class from li and put it on the li where i click then i want the radio button be checked

Any body can help me on this?

js assign new input value to form object without enforcing datetime-local format

The datetime-local html input type accepts a value in the format 2021-12-04T18:45, however my app uses dates in the 2021-12-04 18:45 format, so I’m trying to change the value of the datetime-local input with JavaScript on form submit:

document.getElementById('myform').onsubmit = (event) => {
    let _form = event.target;
    _form.elements.namedItem('date_from').value = '2021-12-10 20:50';
};

but get the following error:

The specified value “2021-12-10 20:50” does not conform to the
required format. The format is “yyyy-MM-ddThh:mm” followed by
optional “:ss” or “:ss.SSS”.

How do I bypass the formatting enforcement in this scenario?

I’d prefer using datetime-local input type, to take advantage of the built-in date and time picker as opposed to having to use extra library. So changing the input field type would not be a preferable solution.

P.S. I cannot control the backend processing of the form, so I have to change the value in the frontend before the form is submitted further.

Unclear why Fetch for UPS XML API failing

I’m working on an airtable automation that is putting in an address validation request to the USPS API. For some reason, when I try to fetch it times out. I’ve validated that the URL I’m testing on works just fine and provides a response, but no matter what I try, I cannot get this to work.

AFAIK, using Fetch is the only way I can access the XML response in airtable automations. I’m open to anything that gets me the data (I know that because it’s an XML response I can’t parse it immediately.)

Here’s an example of a URL (with my ID marked out) that is failing:

let geo2 = await fetch( 'http://secure.shippingapis.com/ShippingAPI.dll?API=Verify&XML=<AddressValidateRequest%20USERID="00000000"><Address><Address1>null</Address1><Address2>7400%20Quebec Pl NW</Address2><City>Brooklyn</City><State>NY</State><Zip5>20202</Zip5><Zip4></Zip4></Address></AddressValidateRequest>').then(response => response.text())

I can’t find any similar errors online, and have found code in other places (not airtable) that has worked. Any idea why this isn’t working, and if there are alternatives that work in airtable? I can’t use XMLhttpRequest as far as I can tell.

Delete item from table React

I create a table so you can add and remove items. Deletion as far as I understand needs to be done through the .filter() for the unique id of each item I apply Date.now(). The problem is that I can not pass the value of the id from the child(Li) element to the parent(App). React constantly shows the error that deleteRow is not a function. As if I understand that it is a parameter but how then can it be called. Thank you to everyone who responds !!!

App.js

import { Button } from 'primereact/button';
import './App.css';
import Li from './components/Li'
import './component_style/Ul.css'
import { useState } from 'react';


function App() {
 let tableId = 0 ;
    const [tableRows, setTableRows] = useState([
      {
        id: Date.now(),
        firstName: "lorem",
        secondName: "lorem",
        lastName: "lorem"}
  ]);
  
    const addNewRow = () =>{
      const newRow = {
        id:Date.now(),
        firstName: "",
        secondName: "",
        lastName: ""
      } 
      setTableRows([...tableRows, newRow])
    }
    
      /////////////////////////////////////////
    function deleteRow(){
      console.log("tableId")
      
    }
    //////////////////////////////////////////

  return (
    <div className="App">
      <Button onClick = {deleteRow}>Add new stroke</Button>
      <ul className = 'ul__box'>
        {tableRows.map((row,id) =>{
          if(row)
          return(<Li row={row} key={id} deleteRows = {deleteRow} />  )
        }
        )}
         
      </ul>
    </div>
  );
}


export default App;

Li.js

import Inputs from './Inputs';
import {Button} from '../../node_modules/primereact/button'
import '../component_style/Li.css'

function Li(props, deleteRows){
    let idTable = props.row.id
    const showProps = () =>{
        console.log(props.row.id)
    }
    ///////////////////
    const removeRow = () =>{
        console.log(idTable) // id Element
        let a = deleteRows.deleteRow(idTable) // non-work code
    }
    ///////////////////
    return(
        <li className = "item_li">
            <Inputs valTable = {props}/>
            <Button  onClick = {removeRow}>Delete</Button>
        </li>
        
    )
}
export default  Li; 


Header tag and paragraph tag are shown in single line tinymce

I’m using TinyMCE in my backend for content entry. But the content are displayed weirdly in the frontend.

I’ve not set any kind of css for this layout.enter image description here

I’m using the following tools and plugins:

menubar: 'file edit view insert format tools table help',
toolbar: 'undo redo | bold italic underline strikethrough | fontselect fontsizeselect formatselect | alignleft aligncenter alignright alignjustify | outdent indent |  numlist bullist | forecolor backcolor removeformat | pagebreak | charmap emoticons | fullscreen  preview save print | insertfile image media template link anchor codesample | ltr rtl',
  toolbar_sticky: true,

This is the project I’m working on.
link

I couldn’t find what is causing the layout issue.

How to separated onclick event in the list of buttons Javascript DOM

I’m a novice to Javscript DOM and try making a Rock Paper Scissors Game. In that game, I want to customize the onclick event that I’m the person who can decide and click on both options among paper, scissors, or rock.

In game.html I have 3 options as 3 button events for each paper, rock, and scissors

<div class="decisions">
            <input
                class="options"
                type="image"
                disabled="true"
                src="./assets/rock.svg"
                value="Rock"
            />
            <input
                class="options"
                disabled="true"
                type="image"
                src="./assets/paper.svg"
                value="Paper"
            />
            <input
                class="options"
                type="image"
                disabled="true"
                src="./assets/scissors.svg"
                value="Scissors"
            />
</div>

main.js

const options = document.querySelectorAll(".options")

const startGame = () => {
    // list of options 
    const _options = ["Rock", "Paper", "Scissors"]
    options.forEach(option => {
        option.addEventListener("click", function () {
             // this is my turn 
            let hInput = this.value
            // this is random turn for computer, but I want to to make this turn
            // by myself
            let cInput = _options[Math.floor(Math.random() * 3)]
            if (hInput && cInput) {
                updateScore(hInput, cInput)
                compareInputs(hInput, cInput)
            }
        })
    })
}

How do I separate the addEventListender to make 2 different turns by myself?

How to integrate 2.5% sales fee in an NFT Marketplace

I’m currenttly building an NFT marketplace, I am done with all the major functionalities, i.e listing, selling, buying etc. but the problem is, when wiriting the code earlier I used a fixed listing fee of 0.1 ether and now I would like to integrate a 2.5% fee on every sale
Here’s my solidity code

function createMarketSale(address nftContract, uint256 itemId, uint256 commission)  
 public  
 payable  
 nonReentrant  
    {  
        uint256 price = idToMarketItem[itemId].price;  
        uint256 tokenId = idToMarketItem[itemId].tokenId;  
 require(  
 msg.value == price,  
 "Please submit the asking price in order to complete the purchase"  
        );  
        idToMarketItem[itemId].seller.transfer(msg.value);  
 IERC721(nftContract).transferFrom(address(this), msg.sender, tokenId);  
        idToMarketItem[itemId].owner = payable(msg.sender);  
        idToMarketItem[itemId].sold = true;  
        _itemsSold.increment();  
 payable(owner).transfer(commission);  
    }

Here’s How my web3 frontend interacts with the contract

async function buyNFT() {
 const web3Modal = new Web3Modal();
 const connection = await web3Modal.connect();
 const provider = new ethers.providers.Web3Provider(connection);

 const signer = provider.getSigner();
 const contract = new ethers.Contract(nftmarketaddress, Market.abi, signer);

 const price = ethers.utils.parseUnits(nft.price.toString(), "ether");
 const fee = +((2.5 / 100) * nft.price);
 let commission = fee.toString();

 let transaction = await contract.createMarketSale(nftaddress, nft.itemId, commission, {
 value: price,
 });

 await transaction.wait();
    window.location.replace("/profile");
 }

but I keep getting an Error: Transaction reverted: function call failed to execute when it gets to this line :

 payable(owner).transfer(commission);  

I have no idea what I’m doing wrong, please help

Optimize Foreach inside another Foreach PHP/Javascript

I need to optimize this code:

<div class="temporadas">
    <?php $i = 0;
    foreach ($temporadas as $temporada) {
        $i++; ?>
        <div data-id="<?= $temporada['temporada']; ?>" class="temporadaBox" onclick="temporadaTab(<?= $temporada['temporada']; ?>)">
            <span class="temporada">
                Temporada <?= $temporada['temporada']; ?>
                <?= (!empty($temporada['nome']) ? '- '.$temporada['nome'].'' : ''); ?>                          
            </span><img id="arrow<?= $temporada['temporada']; ?>" <?= (($i == 1) ? 'class="arrowDown"' : 'class="arrowLeft"'); ?>>
        </div>          
        <div class="temporadaContainer" id="temporadaContainer<?= $temporada['temporada']; ?>" <?= (($i == 1) ? '' : 'style="display:none;"'); ?>>
            <?php foreach ($episodios as $episodio) {
                if ($episodio['temporada'] == $temporada['temporada']) { ?>           
                    <div class="item" data-id="<?= $episodio['episodio']; ?>">
                        <a href="<?= $config['site_url']; ?>/<?= (($temporada['hidden_temporada'] == 1) ? $temporada['url_anime'] : $temporada['url_temporada']); ?>/episodio-<?= encodeInt($episodio['episodio']); ?>/">
                            <img src="<?= $config['site_url']; ?>/images/background_episodios/<?= $episodio['url_anime']; ?>/small/t=<?= $episodio['temporada']; ?>&ep=<?= $episodio['episodio']; ?>.jpg"/>
                            <div class="blank"></div>
                            <div class="titulo">
                                <span class="description"><u>Episódio <?= $episodio['episodio']; ?></u><?= ((!empty($episodio['titulo'])) ? " - ".$episodio['titulo']."" : ""); ?></span>
                                <span class="date"><?= ucfirst(strftime('%b. %d, %Y', $episodio['data'])); ?></span>
                            </div>
                        </a>
                        <div class="clearfix"></div>
                    </div>
                <?php } ?>
            <?php } ?>
        </div>
    <?php } ?>
</div>

Explaining the code, $temporadas have about 20 rows, and $episodios have about 1000 rows..
I need to put each episodio with temporadaID inside current temporada container..

The problem as you can see, is that if we have 20 rows of $temporada and 1000 rows of $episodio, we will loop 20,000 times.

I though in leave $episodio foreach outside $temporada, and organize the episodios with Javascript after complete the loop, however i have no idea how to do it..

Someone could help me? I appreciate, thank you!!

How do I pass a variable value which was collected from user input from one function to another (javascript)

I am trying to create a page on html that automatically creates a pie chart with data provided from the user input form. I am trying to pass the values tax, mort,f,transport,and saving from collect() to drawChart() so that it could use those values to create the pie chart, but it doesn’t seem to work. Does anyone know why?

function collect() {
    var tax = +document.getElementById("taxes").value;
    document.getElementById('tax').innerHTML = tax;

    var mort = +document.getElementById("mortage").value;
    document.getElementById('mort').innerHTML = mort;

    var f = +document.getElementById("food").value;
    document.getElementById('f').innerHTML = f;

    var transport = +document.getElementById("transportation").value;
    document.getElementById('transport').innerHTML = transport;

    var saving = +document.getElementById("savings").value;
    document.getElementById('saving').innerHTML = saving;

    drawChart(tax,mort,f,transport,saving);
}


    function drawChart(val1,val2,val3,val4,val5) {
  
    var data = google.visualization.arrayToDataTable([
    ['Expense/Income', '$ per Month'],
    ['Taxes',val1],
    ['Mortage', val2],
    ['Food', val3],
    ['Transportation', val4],
    ['Savings',val5]
    ]);
var options = {'title':'Monthly Budget', 'width':550, 'height':400};

    // Display the chart inside the <div> element with id="piechart"
    var chart = new google.visualization.PieChart(document.getElementById('piechart'));
    chart.draw(data, options);
    }
<div class="editTable">
  <div class="left">Taxes: </div><div class="right"><input type="number" name="taxes" id="taxes"></div><br><br>
  <div class="left">Mortages: </div><div class="right"><input type="number" name="mortage" id="mortage"></div><br><br>
  <div class="left">Food: </div><div class="right"><input type="number" name="food" id="food"></div><br><br>
  <div class="left">Transportation: </div><div class="right"><input type="number" name="transportation" id="transportation"></div><br><br>
  <button onclick="collect();" class="editRowBtn">Update</button><br><br>
</div>

im getting the error clear missing intends when coding a bot

    const Discord = require("discord.js");

const client = new Discord.Client({ ws: { intents: new Discord.Intents(Discord.Intents.ALL) } });

‘this is a code that requires all intents is it wrong’

client.once('ready', () => {
    console.log('Coleria is online!');
});

const prefix = '*'

‘can i go with this prefix’
client.on(“message”, message =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(" ");
    const command = args.shift().toLowerCase();

    if(command === 'sa'){
        messageCreate.channel.send('As kardeşim hoşgeldin.');
    }
});

client.login("my token");

‘cant give my token xd’

MongoDB aggregate to extract values from a nested array and return a total

I have this collection structure:

[
   "_id": "61a013b59f9dd0ebfd23ftgb",
   "modules": [
     {
       "_id": "61a013b59f9dd0ebfd964dgh",
       "videos": [
         {
           "_id": "213412",
           "progress": 100
         },
         {
           "_id": "61a013b59f9dd0ebfd965f4a",
           "progress": 0
         },
       ]
     },
     {
       "_id": "43556hujferwdhgsdft",
       "videos": [
         {
           "_id": "fdsg3sg98er989890",
           "progress": 66
         },
         {
           "_id": "fdsg3sg98er989890",
           "progress": 100
         },
         {
           "_id": "fdsg3sg98er989890",
           "progress": 100
         }
       ]
     }
   ]
 ]

I am trying to return the overall progress for each “module” by adding up all the videos that have progress of 100 and creating a percentage based on number of videos in the module. For example, the first module should return “module_progess” of 50 within it as this has 1/2 videos completed.

{
   "_id": "61a013b59f9dd0ebfd964dgh",
   "module_progress": 50,
   "videos": [
     {
       "_id": "213412",
       "progress": 100
     },
     {
       "_id": "61a013b59f9dd0ebfd965f4a",
       "progress": 0
     },
   ]
},

How do i access each videos object to make this calculation and add the new field to the response?

How can i add multiple views to one view without conflict on scripts?

I am trying to add multiple views to one view, but it conflicts with scripts and repeating IDs, these are previsualization views before convert to PDF file, these are generating charts.

What i do to add the multiple views is:

 $view .= view('system.administrator.history.pdf.layout-multiple', compact('sample', 'samples', 'tests'))->render(); // These is into a foreach loop
return $view; // This is what i received at the AJAX function and is sended to a form element hidden to send data to a new view

Function to add multiple views at one is working, my problem is with scripts, and IDs.

Any solution?