how to check if button has class and then remove that class javascript

I have a list of buttons and each time one has been clicked I want to check if the one that has been clicked has a certain class name and if it does then only delete class name and not the button. I have looped over the button and then said if the button contains a class but this doesn’t work.

<button class="helpBtn doesHelp">Help</button>
<button class="helpBtn">Help</button>
<button class="helpBtn doesHelp">Help</button>


const helpBtn = document.querySelectorAll('.helpBtn');

for (let h = 0; h < helpBtn.length; h++) {
  helpBtn[h].addEventListener('click', () => {
    if (helpBtn[h].classList.contains('doesHelp')) {
      help[h].classList.remove('doesHelp');
    }
  });
}

is this possible to do?

Cropperjs move to cropp zone

I’m changing the cropper position in the code, and I need it, when I change the cropper position to a position that is not currently visible on the zoomed state, to move it to that position and I would be able to see the cropper.

There are methods like moveTo, but that moves the top left corner of the image, I would need the shift to be functional so that the cropper can be seen in the middle and take into account the zoom of the image.

Are there any sugestion on how to achieve this?

I want to get a message when i don`t put a number in a conditional

const user = "Marta";
let edad=aa;
let descuento = true;
let isNaN = true;
const number= NaN;

if (Number.isNaN(edad)) {
  console.log(`A ${user} no le corresponde ningún descuento`);
} if (edad ===27 && descuento ===true){
 console.log(`A ${user} le corresponde el descuento juvenil(menores de 30 años)`);
}  else if (edad <=12){
    console.log(`A ${user} le corresponde el descuento infantil(menores de 12 años)`);
} else if (edad >60){
    console.log(`A ${user} le corresponde el descuento de jubilados(mayores de 60 años)`);
}

I’ve tried to define a as a not number also or try with a boolean and it’s not working. When I’ change the edad for NaN it doesn´t work. If in edad I put a number it worksyour text

split method not working in node js put operation

I’m providing an update action in my node js project.
I need to update it when data comes through the input, I am facing a problem like this.

If I send a new data via input, the split method works.
But when I send the same data, the split method does not work. What can be the answer to this question? Can you help?

Data format sent;
{ url: '/assets/images/upload/1678259610746.jpg' },{ url: '/assets/images/upload/1678259610749.jpg' }

`
let imageData = req.body?.image.split(‘,’);

const galleryCount = imageData.length;   

for (let i = 0; i < galleryCount; i++) {


  array.push(
    {
      url : imageData[i].split(' ')[2].replace(`'`,'').replace(`'`,''),
    }
  )
 
}

`
The function is as above, if I enter a value in the input and send it, it works and I get the output as follows.

/assets/images/upload/1678259610746.jpg /assets/images/upload/1678259610746.jpg

But when I send the same data again, the function does not work, it gives an output like this.

url: url: url:

A very strange problem that I could not solve.

Using an input to refer to an object in JavaScript

Is there a way to refer to an object by using the input from the user?
Something like this:

var item1 = {
    name: "cake",
    price: 100
}

var item2 = {
    name: "scones",
    price: 10
}

function test(){
    var userInput = document.querySelector(".codeInput").value;
    
    console.log(userInput.price);
}







document.querySelector(".test").addEventListener("click", test);

If a user enters “item1” then 100 should be logged out. So is there a way to have the string “item1” refer to the object item1?

Thanks for the help.

How to correctly transfer the value from html to js? html, node.js

I get the value from an html page, and I want to color the cell in js relative to the received value

For example, ID = 11, hence the 11 cell of the table is decorated

html

<form name="sell">
    <table>
      <tr><td><b>ID: </b></td>
          <td><input name="values" SIZE = 20
                onblur="this.value=this.value.toUpperCase()"></td></tr>
    </table>
    <input TYPE="button" value="Готово" onClick="Complete;">
  </form>
  <table border="1" cellspacing="0" cellpadding="3" >
    <tr>
      <td id="11">11</td>
      <td id="12">12</td>
    </tr>
  </table>
  <script src="/low.js"></script>

js

function Complete(){
    if (typeof document !== "undefined"){
        let fm = document.sell.values.value
        let element = document.getElementById(fm)
        element.style.background = 'black'
    }
}
Complete()

I write in ID 11, but cell 11 is not decorated

How to replace an object in an array with another object?

In vue.js I am looking for a way to replace social in the array with another object’s key with the same value, for example:

netTeams: {
            0: {
                social: 'Twitter',
                name: 'Red',
                id: 32,
                group: 'a'
            },
            1: {
                social: 'Twitter',
                name: 'Green',
                id: 33,
                group: 'b'
            }
        }

and

socials: {
            1: Facebook,
            2: Instagram,
            3: Twitter,
            4: Youtube
        }

the result should be

netTeams: {
        0: {
            social: 3,
            name: 'Red',
            id: 32,
            group: 'a'
        },
        1: {
            social: 3,
            name: 'Green',
            id: 33,
            group: 'b'
        }
    }

I tried a computed property but I get errors. Any advice would be greatly appreciated!

Marker on Gmap API doesn’t show

I’m basically tryin to reproduce the tutorial of Coder Coder : https://youtu.be/CdDXbvBFXLY?t=950
But it seems that I’m getting something wrong putting a marker on my map, as seeable on my screenshots

That’s the code I went with, that I tried to tweak :

<!-----------MAP-------------->
<div id="map"></div>
<script> 
    function initMap() {
        map = new google.maps.Map(document.getElementById("map"), {
         center: { lat: 69.4865, lng: 88.3972 },
         zoom: 13,
         mapId: '5824d85d9a50d553'
        });
     }
    window.initMap = initMap;
 </script>
 <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC9muT1kpa4wAlRV5XmB8Ke4RzArO40Ahk&map_ids=5824d85d9a50d553&callback=initMap">           
</script>

<!-----------MARKERS--------------> 
<script> 
 var marker = new google.maps.Marker({
        position: { lat: 69.49314543445847, lng: 88.39728059961243 },
        map,
        title: "Hello World!",
        });
</script>

Thank you for your help !

How do I fix webhook URL (fetch) not sending data to Slack Channel using JavaScript?

I’m trying to send a the data to a slack channel using this code every time the script is being used. All the variables set from that channel match to JSON.stringify below. Problem is, everytime the page loads and my javascript works, below doesn’t send any data to my Slack Channel. I have researched similar issues but I could not find the solution that works for me.

Any input will be highly appreciated. Thank you very much in advance.

function Log() {
    const ticketurl = window.location.href;
    const data = `${ticketurl} `;
    const date = `${new Date().toISOString()} `;
    const ver = `${scriptver} `

    let id;

    if (A === true) {
        id = document.getElementsByClassName('sim-navDropdown--user')[0].innerText;
    } else if (B === true) {
        id = document.getElementsByClassName("dropdown")[4].innerText;
    }

    fetch('https://hooks.slack.com/workflows/test', {
          method: 'POST',
          headers: {
             'Accept': 'application/json, text/plain, */*',
             'Content-Type': 'application/json'
        },
        body: JSON.stringify({ "Content": data, "Date": date, "Version": ver, "id": id })
    }).then(res => res.json())
      .then(res => console.log(res));
}

iMacros to JS, how possible is it to convert and implement?

Yeah, so I’m new here, uhm, I have a question or two about website automation.
One, if I make a recording of my actions on my website with iMacros, can I convert the generated code to JavaScript?
Two, if I can, can I add the JavaScript code to my website’s code directly and make my actions replicated whenever another user visits my website?

I asked my elder sister already, she’s actually unsure, so she said to check StackOverflow, I legit just created my account for this like 5 minutes ago

How to repeat an action of finding and clicking an element using javascript

I am trying to write some piece of code that visits a specific page by searching through the pagination element and clicking on a specific page. Then the code clicks on the view buttons one by one. After clicking a single view button, it copies the url on the next page and clicks close button and repeats the same process.

The challenge I am having is I need to visit the specified page each time – just before clicking any view button. The reason is even if I am on say, page 10 and click to copy the link, then click the close button, the page redirects me back to the default page i.e page 1. That is the default behaviour of the page that I am working on. So to avoid that, I have to return to the specific page (in my code example, page 2) each time I want to click the view button so that the code fetches the content on page 2 and not page 1. The first time the code works well and fetches the first row of page two but the subsequent rows are for page one because the default page behaviour takes over. This is what I want to avoid.

I added the code just before the code clicks on the viewButton.click(); but it does not work and stops clicking on the next view buttons completely. I am stuck hope someone could take a look.

What I have so far (*Added many comments to help quickly understand what’s happening):

// Get a reference to the pagination container
const pagination = document.querySelector('.e-pager');

// Function to click on the next page button and check for the target element
function clickAndCheck() {
  // Get a reference to the next page button
  const nextButton = pagination.querySelector('.e-next.e-icons.e-icon-next.e-nextpage.e-pager-default');
  // Click on the next page button
  nextButton.click();
  // Check if the target element is now visible
  const targetElement = pagination.querySelector('a[index="2"]');
  if (targetElement !== null) {
    // Click on the target element
    targetElement.click();

    // Wait for 5 seconds before running the second code
    setTimeout(runSecondCode, 5000);
  } else {
    // If target element is not yet visible, repeat the process after 2 seconds
    setTimeout(clickAndCheck, 2000);
  }
}

// Start the process by clicking on the next page button
clickAndCheck();

// Function to process rows
function processRows() {
  var currentRowIndex = 0;

  function processNextRow() {
    // Find the "View" button element for the current row
    var viewButton = document.querySelector(`tr.e-row[aria-rowindex="${currentRowIndex}"] b[style="color: blue; cursor: pointer;"]`);

    // If there is no next row, show alert and exit the function
    if (!viewButton) {
      alert("No More Tenders");
      return;
    }

    // Get a reference to the next page button
  const nextButton = pagination.querySelector('.e-next.e-icons.e-icon-next.e-nextpage.e-pager-default');
  // Click on the next page button
  nextButton.click();
  // Check if the target element is now visible
  const targetElement = pagination.querySelector('a[index="2"]');
  if (targetElement !== null) {
    // Click on the target element
    targetElement.click();

    // Wait for 5 seconds before running the second code
    setTimeout(runSecondCode, 5000);
  } else {
    // If target element is not yet visible, repeat the process after 2 seconds
    setTimeout(clickAndCheck, 2000);
  }

    // Simulate a click on the "View" button for the current row
    viewButton.click();

    // Wait for 10 seconds before extracting the link and clicking the "Close" button
    setTimeout(function() {
      // Find the link element
      var linkElement = document.querySelector('td[colspan="3"] a[href^="https://tenders.go.ke/OneTender/"]');

      // Extract the link from the href attribute
      var link = linkElement ? linkElement.getAttribute("href") : null;

      // Simulate a click on the "Close" button
      var closeButton = document.querySelector('button.btn.btn-warning.p-2[type="button"][style*="background-color: rgb(245, 156, 26)"]');
      closeButton.click();

      // Do something with the link
      console.log(link);

      // Increment the row index for the next loop
      currentRowIndex++;

      // Process the next row after 1 second
      setTimeout(processNextRow, 5000);

    }, 500);
  }

  // Start processing the rows
  processNextRow();
}

// Function to run the second code
function runSecondCode() {
  processRows();
}

How to tamil font in export CSV file. we are facing ? error

We are trying so many ways tamil content show like in csv file ” தூதà¯à®¤à¯à®•à¯à®•à¯à®Ÿà® ” please help me .

 mysqli_set_charset($db, "utf8mb4");
$query = $db->query("$reports");

if($query->num_rows > 0){
    $delimiter = ",";
    $filename = "report_" . date('Y-m-d') . ".csv";

    // Create a file pointer
    $f = fopen('php://memory', 'w');

    // Set column headers
    // $fields = array('ID', 'FIRST NAME', 'LAST NAME', 'EMAIL', 'GENDER', 'COUNTRY', 'CREATED', 'STATUS');
    $fields = array('Ticket No','Name','Phone','Zone','Ward','Street','Department','Category','Description','Asgn. Employee','Date','Overdue Date','Status Updated On','Status');

    fputcsv($f, $fields, $delimiter);

    // Output each row of the data, format line as csv and write to file pointer
    while($row = $query->fetch_assoc()){
        $count = 0 ;
        $status = ($row['status'] == 1)?'Active':'Inactive';
        $lineData = array($row['ticket_id'], $row['empname'], $row['COMP_MOB'], $row['zone_name'], $row['ward_name'],$row['ASSN_STREET'], $row['name'], $row['complaint_cat_name'], $row['DEPT_DESCRIPTION'], $row['emp_name'],$row['dateofsubmit'],$row['overdue'],$row['dateofupdate'],$row['STATUS']);
        fputcsv($f, $lineData, $delimiter);
    }

    // Move back to beginning of file
    fseek($f, 0);

    // Set headers to download file rather than displayed
 header('Content-Type: text/csv');
 header('Content-Encoding: UTF-8');
  
    header('Content-Disposition: attachment; filename="' . $filename . '";');
    //output all remaining data on a file pointer

    fpassthru($f);
}
exit;
?>

enter image description here

After export csv we need tamil font

Assigning outer variable from function return value shows “undefined” [duplicate]

I am working on an Node JS with Express API. After getting data from MySQL database, the response data must be pass in the variable outside the function.

Here is the primary function:

function get_orders(callback) {
  dbConnection.query(
    "CAll orders.getOrders()",
    async (err, rows, fields) => {
      if (!err) {
        if (rows.length !== 0) {
          return await callback(rows[0][0]);
        }
      } else {
        throw err;
      }
    }
  );
}

Here were I call the primary function:

function call_orders(req, res) {
  let data;
  get_orders(async (result) => {
    data = await result;
  });
}

I was assuming that data variable will have the values from get_orders() function but unfortunately its shows ‘undefined’.

How to return the value in a function using javascript

For the below function im trying to return a value which is arr after pushing the a to it but the result is nothing but if we console for the same then the data is printing after calling the function. Can you please let me know why it is happening and whats the possible solution or it.

function name() {
  let a = {
    "a-y-z": {
      "abc": "acb"
    }
  }
  let arr = [];
  arr.push(a)
  return arr;
}

console.log(name());