How prevent reload after post request?

I am trying to make a post request to the server and do something with the response. Things seem to work on the server-side. The problem is that the page reloads upon completion of the response and I cannot do anything with the response.

The common suggestions are using button or preventDefault. These suggestions do not solve the problem: as you can see below, the input type is button (not submit) and preventDefault() on the event does not work.

Does anyone have an idea about what I am missing?

 <form id="modelCodeForm">
    <label for="codehere"></label>
    <div id="modelAreaDiv">
      <textarea id="modelArea" cols="60" rows="20">
stuff
      </textarea>
      <br>
      <input id="submitUserModel" type="button" value="run on server">
  </div>
  </form>
function initializeUserModel(){
  let model = document.getElementById("modelArea").value;
  fetch('http://localhost:8080/', {
      method: 'post',
      headers: {'Content-Type': 'text/plain'},
      body: model
    })
      .then(response => response.json())
      .then(data => {
        console.log(data);
      }).then(console.log("received!"))     
}  

Call JS function on click of a button in a Bootstrap modal

I have a bootstrap modal, where I have few buttons to capture feedback.

I want to call a JS function on click of one of the buttons.

However, on click of the button, the modal just closes without calling the JS Function.

But, if I do the same onclick event on any other element not in the modal, it works fine.

js

<script>
          
   function sayHello() {
        alert("Demo Alert")
   }
</script>

HTML

<div
class="modal fade"
id="exampleModal"
tabindex="-1"
role="dialog"
aria-labelledby="exampleModalLabel"
aria-hidden="true"
>
<div
  class="modal-dialog modal-lg modal-dialog-centered"
  role="document"
>
  <div class="appie-signup-area">
    <div class="container">
      <div class="row">
        <div class="col-lg-12">
          <div class="appie-signup-box">
            <h3 class="title">How was the Session?</h3>
            <form action="#" id="mood-tracker">
              <div class="row">
                  <div class="input-box">
                    <button type="submit" value="Good" onclick="sayHello()">
                      <i
                        class="fa fa-smile"
                       
                      ></i
                      >Good
                    </button>
                  </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</div>

Where am I going wrong?

Draw lines and set stacking angles between them

I want to draw a set of lines on a canvas with plain javascript. And I want those lines to be stacked on each other. The tricky thing is, that I want to set an angle between each line and I want the angle to be based on the previous angles. So if line1 has an angle of 15° and line1 one of 15° aswell. line2 should be rotated for 30°.

I made a quick sketch in paint to visualize my description:
Image of my goal crappily drawn in paint

I also made a condesandbox and tried it. Each slider should be the angle of one connection point. The first line (red) works just as expected. If you increase the angle, the line is drawn in that angle. But the next lines are not connected at all and I do not know how to fix this.
https://codesandbox.io/s/angled-lines-1p0yz?file=/src/index.js
CodeSandbox Screenshot

JS Choosen show option according to data-attribute

In my web app I have a choosen dropdown (second) which has its options with some data-attr that depend of another dropdown (first).

My requirement is, when the user selects a value on the first dropdown, the second one only show the options that have the data-attribute equal to the value that the user selected on the first drodpdown.

My question is, how to show only those options.

I have the code to hide all, and its working fine, what I can´t seem to do is to select only the options with the data-attribute selected and show the-

code to hide all options:

v_reset = function () {
        $("#div_select").each(function () {
            $(this).children("option").hide();
        });
    
        $('#div_select').trigger('chosen:updated');
    }

js function to change the second dropdown:

v_change = function () {
    let selectedValue = $("[id*=firstSelect] :selected").val();
    if (selectedValue > 0) {
        v_reset();

        var optionsArray = getAllElementsWithAttribute('data-search', selectedValue);
        for (let i = 0; i < optionsArray.length; i++) {
            console.log($(this));
            let value = optionsArray[i].value;
            //select all options with data-search attr equals to the selected value
            //$("#div_select option[='"+ selectedValue+ "']").show();
            $('#div_select').trigger("choosen:updated");
        }
};

select html:

<select id="div_select" class="chosen-select form-control" onchange="v_change(this)" ">
        <option value="-1">Selecionar opção</option>
        <option data-search="" value="23">JMM</option>
        <option data-search="" value="1037">Rota 20</option>
        <option data-search="" value="1572">entrega</option>
        <option data-search="" value="2227">29JUN19</option>
        <option data-search="" value="2417">teste</option>
        <option data-search="1" value="2450">18OUT16</option>
        <option data-search="10098" value="2871">18OUT16</option>
        <option data-search="17079" value="2917">Luis</option>
        <option data-search="17079" value="2918">Luis</option>                              
        <option data-search="17079" value="2940">teste tablet</option>
     </select>

Detect when content overflow

I want to add a specific styling when my content is overflowing. The styling I would like to add is a shadow that will indicate that you can scroll to see more information.

My question is: How can I detect that my content is overflowing to add this style only when it is overflowing?

Reading a text file and converting to form another text file

I have programming experience and am fairly new to JS would like to read a text file line by line into an array. Then convert the array elements and output to another text file. Now I am going through https://www.w3schools.com/js/default.asp

I am thinking of reading one line at a time and putting that line into array and then loop the process to read the whole file .
Lines would like this
saa-ree-|gaa-maa-|paa-daa-|nee-Saa-|

and then have a code to process the array to produce
CD|EF|GA|Bc|

Thank you

Thiru

a very small simple complete example

input

saa-ree-|gaa-maa-|paa-daa-|nee-Saa-|

Saa-nee-|daa-paa-|maa-gaa-|ree-saa-|

output

CD|EF|GA|Bc|

cB|AG|FE|DC

Text is shaking after using useEffect in Next JS

text is shaking after scrolling

this is my code:

const [scroll, setScroll] = useState(0);



useEffect(() => {
    window.addEventListener("scroll", handleScroll);
    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  });

  function handleScroll() {
    setScroll(
      window.scrollY ||
        window.scrollTop ||
        document.getElementsByTagName("html")[0].scrollTop,
      document.documentElement.style.setProperty("--scroll-var", scroll + "px")
    );
  }

I don’t know what missing. but it make all my text shaky after render it and start after scrolling the page.

so sorry im newbie here.

Get selected value from dropdown list

I am trying to get the selected value from the dropdown, but have no luck.

<select class="form-control" name="cars" onchange="getAvailableCars();">
   <?php getCars() ?>
</select>

getCars() function retrieves all available cars from the database, and they show in the dropdown menu.

Here is function getCars()

function getCars(){
    $link = new mysqli("localhost", "root", "", "cars");
    $link->set_charset("utf8");

    $sql=mysqli_query($link, "SELECT CarID, CarCode, CarName FROM cars a WHERE CarAvailable = 1");

    echo '<option value="">Select </option>';
    while($record=mysqli_fetch_array($sql)){
        echo '<option value= "' .$record['CarID']. '">' . $record['CarCode'] ."-|-". $record['CarName'] .' </option><br/>';
    }
}

Then I created JS function which will get selected Card ID from the select menu.

<script>
    function getAvailableCars() {

        var car = document.getElementById("cars");
        var selectedCar= car.options[car.selectedIndex].value;

        console.log(selectedCar);
        /*
        var arr = {artikal:selectedCar};
        $.ajax({ url: 'available-cars.php?a=1',
            data: arr,
            type: 'post',
            success: function(output) {
                document.getElementById("cars").value = output;
            }
        });
        */
    }
</script>

Console displays issue:

Uncaught TypeError: Cannot read properties of null (reading 'options')

Also, I have tried with Jquery, but I got in console undefined.

var cars = $("#cars:selected").val(); 

I was following link below, any other too but for some reasons, I cannot get the selected value:
get-selected-value-in-dropdown-list-using-javascript

input.type = “number”; but only for specific input field

How I can use my : input.type = "number"; to be used only in specific fields?

            var cell1 = row.insertCell(0);
            var cell2 = row.insertCell(1);
            var cell3 = row.insertCell(2);
            var cell4 = row.insertCell(3); 

I have these inserts, to insert fields into the table. So how can I specify only for the eg. Cell(0)? To have only numbers (0-9) in the specific fields.

Sorry if sounds stupid.
Thank you

why class not render after set state in react js?

I want to add an active class to the indicator after clicking it but the active class doesn’t render even though list.id === active

const [active, setActive] =  useState(1);

const scrollToElement = (id, value) => {
    const element = document.getElementById(`${value}`);
    element.scrollIntoView({ behavior: 'smooth' });

    setActive(prevState => {
      return {
        ...prevState,
        active: id
      }
    });
  }
  
<div
  key={list.id}
  className={`${list.id === active ? `${style.active} ${style.dot}` : `${style.dot}`}`}
  onClick={() => scrollToElement(list.id, list.name)}
/>

Using ngx-translate to display images

I would like to use ngx-translate inside my Angular app to display a language-specific image. In my case its a Logo which is displayed in different languages and styles depending on the used language.

I did already tried with

        <img style="width: 100px" [attr.src]="'branding.logo' | translate" alt="" class="src" />

Where branding.logo refers to a URL of the particular logo in the web.

But Chrome displays, that it couldn’t find the requested ressource at: ‘https://localhost:8100/branding.logo’.

What am I doing wrong?

How to set useReducer initial state using API response?

I’m new to React and trying to build an app with a cart feature where users can add robots to the cart. I’m using Context API to provide cart across the app and useReducer for states. The robots are being fetched from a server and load just fine. But I can’t seem to find a way to set the initial state of the reducer using fetched products. The state always returns an empty array for robots. How to solve this?

const CartProvider = ({ children }) => {
    const [robots, setRobots] = useState([]);

    useEffect(() => {
        fetch('http://localhost:8000/api/robots')
            .then(res => res.json())
            .then(data => setRobots(data?.data))
    }, [])

    const initialState = {
        robots: [...robots],
        cart: []
    }
    const [state, dispatch] = useReducer(cartReducer, initialState);

    return (
        <CartContext.Provider value={{ state, dispatch }}>
            {children}
        </CartContext.Provider>
    );
}
export default CartProvider;

Why Data is missing simultaneously when app script running & sometimes vanished from the whole spreadsheet & found no where

I have some issue where i had written a script that on the basis of a particular value of a row it should move to the specific sheet but dramatically it disappear simultaneously sometimes it work good & sometimes it vanished that row & can’t find anywhere in the spreadsheet where it had gone no one knows & even in some cases it automatically disappear or move the row by itself even if it is not defined to do so. Function is written below please help to rectify it.

function onEdit(e)
{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Delhi Calls Asha");
  var values = sheet.getRange(1, 4, sheet.getLastRow(), 1).getValues();
  var moveRows = values.reduce(function(ar, e, i) {
    if (e[0] == "LG") ar.push(i + 1);
    return ar;
  }, []);
  var targetSheet = ss.getSheetByName("DELHI Calls Amit");
  moveRows.forEach(function(e) {
    sheet.getRange(e, 1, 1, sheet.getLastColumn()).moveTo(targetSheet.getRange(targetSheet.getLastRow() + 1, 1));
  });
  moveRows.reverse().forEach(function(e) {sheet.deleteRow(e)});
}


{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Delhi Calls Amit");
  var values = sheet.getRange(1, 22, sheet.getLastRow(), 1).getValues();
  var moveRows = values.reduce(function(ar, e, i) {
    if (e[0] == "Cancelled") ar.push(i + 1);
    return ar;
  }, []);
  var targetSheet = ss.getSheetByName("Happy Calling Delhi");
  moveRows.forEach(function(e) {
    sheet.getRange(e, 1, 1, sheet.getLastColumn()).moveTo(targetSheet.getRange(targetSheet.getLastRow() + 1, 1));
  });
  moveRows.reverse().forEach(function(e) {sheet.deleteRow(e)});
}

{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Delhi Calls Amit");
  var values = sheet.getRange(1, 22, sheet.getLastRow(), 1).getValues();
  var moveRows = values.reduce(function(ar, e, i) {
    if (e[0] == "Closed") ar.push(i + 1);
    return ar;
  }, []);
  var targetSheet = ss.getSheetByName("Happy Calling Delhi");
  moveRows.forEach(function(e) {
    sheet.getRange(e, 1, 1, sheet.getLastColumn()).moveTo(targetSheet.getRange(targetSheet.getLastRow() + 1, 1));
  });
  moveRows.reverse().forEach(function(e) {sheet.deleteRow(e)});

}
{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Delhi Calls Asha");
  var values = sheet.getRange(1, 22, sheet.getLastRow(), 1).getValues();
  var moveRows = values.reduce(function(ar, e, i) {
    if (e[0] == "Cancelled") ar.push(i + 1);
    return ar;
  }, []);
  var targetSheet = ss.getSheetByName("Happy Calling Delhi");
  moveRows.forEach(function(e) {
    sheet.getRange(e, 1, 1, sheet.getLastColumn()).moveTo(targetSheet.getRange(targetSheet.getLastRow() + 1, 1));
  });
  moveRows.reverse().forEach(function(e) {sheet.deleteRow(e)});
}

{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet4 = ss.getSheetByName("Delhi Calls Asha");
  var values4 = sheet4.getRange(1, 22, sheet4.getLastRow(), 1).getValues();
  var moveRows4 = values4.reduce(function(ar, e, i) {
    if (e[0] == "Closed") ar.push(i + 1);
    return ar;
  }, []);
  var targetSheet4 = ss.getSheetByName("Happy Calling Delhi");
  moveRows4.forEach(function(e) {
    sheet4.getRange(e, 1, 1, sheet4.getLastColumn()).moveTo(targetSheet4.getRange(targetSheet4.getLastRow() + 1, 1));
  });
  moveRows4.reverse().forEach(function(e) {sheet4.deleteRow(e)});
}

{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet5 = ss.getSheetByName("MUMBAI Calls");
  var values5 = sheet5.getRange(1, 22, sheet5.getLastRow(), 1).getValues();
  var moveRows5 = values5.reduce(function(ar, e, i) {
    if (e[0] == "Cancelled") ar.push(i + 1);
    return ar;
  }, []);
  var targetSheet5 = ss.getSheetByName("Happy Calling Mumbai");
  moveRows5.forEach(function(e) {
    sheet5.getRange(e, 1, 1, sheet5.getLastColumn()).moveTo(targetSheet5.getRange(targetSheet5.getLastRow() + 1, 1));
  });
  moveRows5.reverse().forEach(function(e) {sheet5.deleteRow(e)});
}

{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet6 = ss.getSheetByName("MUMBAI Calls");
  var values6 = sheet6.getRange(1, 22, sheet6.getLastRow(), 1).getValues();
  var moveRows6 = values6.reduce(function(ar, e, i) {
    if (e[0] == "Closed") ar.push(i + 1);
    return ar;
  }, []);
  var targetSheet6 = ss.getSheetByName("Happy Calling Mumbai");
  moveRows6.forEach(function(e) {
    sheet6.getRange(e, 1, 1, sheet6.getLastColumn()).moveTo(targetSheet6.getRange(targetSheet6.getLastRow() + 1, 1));
  });
  moveRows6.reverse().forEach(function(e) {sheet6.deleteRow(e)});
}

{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet7 = ss.getSheetByName("Happy Calling Delhi");
  var values7 = sheet7.getRange(1, 31, sheet7.getLastRow(), 1).getValues();
  var moveRows7 = values7.reduce(function(ar, e, i) {
    if (e[0] == "satisfied") ar.push(i + 1);
    return ar;
  }, []);
  var targetSheet7 = ss.getSheetByName("Main Sheet Mix");
  moveRows7.forEach(function(e) {
    sheet7.getRange(e, 1, 1, sheet7.getLastColumn()).moveTo(targetSheet7.getRange(targetSheet7.getLastRow() + 1, 1));
  });
  moveRows7.reverse().forEach(function(e) {sheet7.deleteRow(e)});
}

{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet8 = ss.getSheetByName("Happy Calling Delhi");
  var values8 = sheet8.getRange(1, 31, sheet8.getLastRow(), 1).getValues();
  var moveRows8 = values8.reduce(function(ar, e, i) {
    if (e[0] == "SATISFIED") ar.push(i + 1);
    return ar;
  }, []);
  var targetSheet8 = ss.getSheetByName("Main Sheet Mix");
  moveRows8.forEach(function(e) {
    sheet8.getRange(e, 1, 1, sheet8.getLastColumn()).moveTo(targetSheet8.getRange(targetSheet8.getLastRow() + 1, 1));
  });
  moveRows8.reverse().forEach(function(e) {sheet8.deleteRow(e)});
}

{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet9 = ss.getSheetByName("Happy Calling Mumbai");
  var values9 = sheet9.getRange(1, 31, sheet9.getLastRow(), 1).getValues();
  var moveRows9 = values9.reduce(function(ar, e, i) {
    if (e[0] == "satisfied") ar.push(i + 1);
    return ar;
  }, []);
  var targetSheet9 = ss.getSheetByName("Main Sheet Mumbai");
  moveRows9.forEach(function(e) {
    sheet9.getRange(e, 1, 1, sheet9.getLastColumn()).moveTo(targetSheet9.getRange(targetSheet9.getLastRow() + 1, 1));
  });
  moveRows9.reverse().forEach(function(e) {sheet9.deleteRow(e)});
}

{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet10 = ss.getSheetByName("Main Sheet Mumbai");
  var values10 = sheet10.getRange(1, 58, sheet10.getLastRow(), 1).getValues();
  var moveRows10 = values10.reduce(function(ar, e, i) {
    if (e[0] == "Reopen") ar.push(i + 1);
    return ar;
  }, []);
  var targetSheet10 = ss.getSheetByName("MUMBAI Calls");
  moveRows10.forEach(function(e) {
    sheet10.getRange(e, 1, 1, sheet10.getLastColumn()).moveTo(targetSheet10.getRange(targetSheet10.getLastRow() + 1, 1));
  });
  moveRows10.reverse().forEach(function(e) {sheet10.deleteRow(e)});
}

{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet11 = ss.getSheetByName("Happy Calling Mumbai");
  var values11 = sheet11.getRange(1, 31, sheet11.getLastRow(), 1).getValues();
  var moveRows11 = values11.reduce(function(ar, e, i) {
    if (e[0] == "SATISFIED") ar.push(i + 1);
    return ar;
  }, []);
  var targetSheet11 = ss.getSheetByName("Main Sheet Mumbai");
  moveRows11.forEach(function(e) {
    sheet11.getRange(e, 1, 1, sheet11.getLastColumn()).moveTo(targetSheet11.getRange(targetSheet11.getLastRow() + 1, 1));
  });
  moveRows11.reverse().forEach(function(e) {sheet11.deleteRow(e)});
}

{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet12 = ss.getSheetByName("Main Sheet Mix");
  var values12 = sheet12.getRange(1, 58, sheet12.getLastRow(), 1).getValues();
  var moveRows12 = values12.reduce(function(ar, e, i) {
    if (e[0] == "Reopen") ar.push(i + 1);
    return ar;
  }, []);
  var targetSheet12 = ss.getSheetByName("DELHI Calls Asha");
  moveRows12.forEach(function(e) {
    sheet12.getRange(e, 1, 1, sheet12.getLastColumn()).moveTo(targetSheet12.getRange(targetSheet12.getLastRow() + 1, 1));
  });
  moveRows12.reverse().forEach(function(e) {sheet12.deleteRow(e)});
}

key charCode for virtual keyboard

I have the below code to allow the user input only numbers, this works in browser. But when I access on mobile I think I am not able to get the right key code. So what are the keycodes for the same. Isn’t same as the web.

  // block e char, dot, hiphen and spacebar
  if (event.key === 'e' || [46, 45, 32].includes(event.charCode)) {
    event.preventDefault();
  }else{
   // allow to input logic
}

What are the charCode for dot, hiphen and spacebar which will work for both web and mobile keypad ?

Any help is appreciated

Refreshing UI parts on each loop of an AJAX sync call

Okay, it might be a simple question, but so far I didn’t find anything helpful by searching, so I am giving it a try here.

I am using plain old javascript/jquery on asp.net core on some project I am working on.

I am currently performing some actions on some employees in a foreach loop.
For each employee I am calling synchronously via ajax an API.

What I want is the UI to be updated, showing the current employee being processed in a progress bar.

While on debug, the process seems to work fine, but during normal process, it seems that the UI thread is not updated, only after all the work has been done. As such, as soon as I start processing the employees, the screen is stuck and closes after the work has been done. No progress bar is shown.

I only managed to show the progress animation and the first employee using the below trick

$('#applyYes').click(function (e) {
   e.preventDefault();

   var year = $('#yearCombo').val();

   $('#applyInfo').hide();
   $('#applyLoad').show();
   $('#applyAction').prop('innerText', 'Calculating...');

   setTimeout(function () {

      var employeeIDs = multipleEmployees_Array();
      for (var i = 1; i <= employeeIDs.length; i++) {
         employeeID = employeeIDs[i - 1];
         applyAmount(employeeID, year); //1. Updates progress bar 2. Ajax sync call
      }

   }, 0);

})

As far as I understand the e.preventDefault seems to move the timeout function being processed after UI thread finishes.

What is the optimal way of achieving what I want?

PS: No external libraries if possible. I am working on an third-party platform, that makes it difficult to add external libraries (policies, permissions etc.)