Input values from js are not sent to the model but they are in input

I have code in JS that populates input fields in a form. The code fills in the data correctly but when I upload the model to the server the data is default instead of what I have entered in the fields. How to solve this?

My js code:

$('input[name="datefilter"]').on('apply.daterangepicker', function(ev, picker) {
      $(this).val(picker.startDate.format('DD/MM/YYYY') + ' - ' + picker.endDate.format('DD/MM/YYYY'));

      StartOfReservation.value = picker.startDate.format('YYYY-MM-DD');
      EndOfReservation.value = picker.endDate.format('YYYY-MM-DD');//.trigger("change"); - doesnt work

  });

How to create a websocket server in flutter? Or another technology?

I want to communicate in realtime between a local website and the flutter app without having a central server… In my opinion it is the best way to use a websocket server on the flutter app and connect to it via js, does anybody how to host one?

I’ve already googled very much, but I only found someone who said, that you should use tcp socket, but this wouldn’t work with js…

Random Number Generator with weighted range

I’d like to generate a random number between min and max limits, but with a weighted probability applicated to the range the number is in.

For instance:

const ranges = [
    {
        min: 0,
        max: 19,
        weight: 0.5, // 50% probability
    },
    {
        min: 20,
        max: 49,
        weight: 0.25, // 25%
    },
    {
        min: 50,
        max: 74,
        weight: 0.17, // 15%
    },
    {
        min: 75,
        max: 89,
        weight: 0.08, // 8%
    },
    {
        min: 90,
        max: 100,
        weight: 0.02, // 2%
    },
];

In my mind, I’d like to pick one of my range according to its weight, then pick a random number in between the selected range, as each number in a set range have the same probability to get picked.

I can’t find a good way to pick one range based on its weight.

how to import require.cache and require.resolve

  • Since i’m using module type in package.json or import instead of require.
  • how can i import require.cache and require.resolve
  • i’m trying to reload a file and update changes made.
// error: require is not defined
delete require.cache[require.resolve(`./index.js`)];
  • I tried till now
// This runs with no issues but doesn't update the changes.
import { resolve } from 'node:path';
const require = createRequire(import.meta.url);
delete require.cache[resolve(`./index.js`)];
  • without path
const require = createRequire(import.meta.url);
delete require.cache[require.resolve(`./index.js`)];
  • But this doen’t update the changes made in index.js

Expected Result

  • If i reload specific file and it should update the changes made to file (index.js).

HTML / JavaScript = Age Group Identifier Code *problem

I am trying to do an activity in my web development class but I’ve ran into a problem that looks so simple but I seem to can’t get my head around it. I’ve tried other solutions but still don’t get what’s wrong or lacking in my code.

I want my program to analyze the age and identify it, to overwrite on the paragraph id of agetext, the age group (children, early working age…)

<html>
<body>
<h1>Age Group Identifier</h1>
<p></p>To find out the category of an age group, please enter the age below.</p>
<form id="agegroupidentifier">
    Age: <input id="agein" type="text"><br>
    <input type="button" onclick="ageInput();" value="Submit">
    <p ="agetext"></p>
</form>
<script>
    function ageInput() {
var ageInp=document.getElementById("agein").value;
    }
        if (agein =< 14) {
        document.getElementById("agetext").innerHTML="Children";
        }
        else (agein =< 24)
        document.getElementById("agetext").innerHTML="Early Working Age";
                }
        else (agein =< 54)
        document.getElementById("agetext").innerHTML="Prime Working Age";
                }
        else (agein =< 64)
        document.getElementById("agetext").innerHTML="Mature Working Age";
                }
        else (agein > 64)
        document.getElementById("agetext").innerHTML="Elderly";
    }
</script>
</body>
</html>

React: Passing value from child component to parent component

I have a textbox which conatins data from api call.Then the user can edit this textbox . i want to get the edited text to send it back by api call. The value is always sent empty.Can anyone help me in that?

Child Component

export default function RulesText({ruleText, readOnlyStatus, onChange}:{ruleText:string, readOnlyStatus:boolean, onChange:(val:string) => void}) {
    
    const[textValue, setTextValue] = useState(ruleText)
    
    return (
    <div>
        <textarea  
                readOnly={readOnlyStatus}
                value={textValue}
                onChange={(e) => {setTextValue(e.target.value)}}
            />
    </div>
  )
}

Parent Component

const[editedRuleText, setEditedRuleText] = useState('')

<RulesText ruleText={rules[1].substring(rules[1].indexOf(":") + 1)} readOnlyStatus={isEditing ? false : true} onChange={(val:string) => {setEditedRuleText(val); console.log('Val Now' + val)}}/>

How to create, install and import local typescript package

I’m trying to make a package in typescript, this one in particular. But after installing it locally in my project with yarn add file:../parascan-js, I can’t import the modules correctly. I expect import options to be parascan/components/* (name changed from uikit) but what I see are the file/folders in the root such as src, dist, tsconfig etc. I want to be able to import with

import {Table} from "parascan/components/info"

Instead of this, which gives a lot of error related to my parascan package.

import Table from "parascan/src/components/info/Table"

I’ve tried building dist folder with tsc and babel. Made some changes to package.json by adding type: module and module: dist/index.js but nothing worked.

Change options while the select box is in focus with Javascript

I have a login page where a html select element is updated every second to disable and/or rename the specific element.

Everything works but if you have e.g. an iPad you can focus the select element and then its not getting updated anymore until it loses the focus. And I have no idea on how to proceed from here.

that is the function which is called every second.

function editSelectMenu() {
    countedits = 2;
    const el = document.getElementById('stand');
    cams.forEach (element => {        
        if(cams[countedits - 2].shooter != ""){
            el.options[countedits].disabled = true;
            el.options[countedits].innerText = cams[countedits - 2].name + " " + cams[countedits - 2].shooter
        } else {
            el.options[countedits].disabled = false;
            el.options[countedits].innerText = cams[countedits - 2].name
        }
        countedits++;
    })
}

How to capture boolean value from swal() function and return it to a validation function that prevents or allows form submission?

I have the following code structure. I want to be able to capture the true/false value from swal function and return it to validate_empty_fields(). I know the following code only returns a promise object and swal only allows you to nest the true/false code within a then function. Is there a way to return the respective value when a user clicks the cancel or ok button.

function validate_empty_fields()
        {
            
            let x = document.forms["myform"]["title"].value;
            let y = document.forms["myform"]["description"].value;
            let z = document.forms["myform"]["image"].value;
            if(x=="" && y=="" && z== "")
            {
                swal('warning','Atleast one of the fields must be filled');
                return false;
            }
            else if(x=="" || y== "" || z== "" )
            {
                
                return swal({title: 'warning',
                      text: 'Empty fields will be pushed as such',
                      buttons:true}); 
    
            }
    
        }
    </script>
    
    <form action="addpages.php" name="myform" method="POST" onsubmit="return validate_empty_fields()" enctype="multipart/form-data">
        //input fields for title,description and image
      <button id="submit-btn" type="submit" >ADD PAGE</button>   
    </form>

Problems with search input in angular

I want while typing a word, to have items listed with just that word in the title or header. This my method don’t return anything. What shuold i do?

This is my html

<input type="text" (change)="component.performFilter($event)"/>
<div *ngFor="let report of component?.reports" class="pr-5 pt-2" style="width: 350px;">
    <h3>{{report.header | translate}}</h3>
    <ul class="list-unstyled pl-1">
        <li *ngFor="let item of report.items">
            <i class="fa {{item.icon}} mr-h"></i>
            <a class="link" [routerLink]="item.path"> {{item.title}} </a>
            <p *ngIf="item.description" class="text-muted">{{item.description}}</p>
        </li>
    </ul>
</div>

This is my TS

protected reports: Array<ReportItemsModel> = [];
protected filteredReports = [];

_listFilter: string = '';

get listFilter(): string {
    return this._listFilter;
}
set listFilter(value: string) {
    this._listFilter = value;
    this.filteredReports = this.performFilter(value);
}

constructor(
    protected route: ActivatedRoute,
    protected httpService: HttpService
) {
    super(route);

    this.titleIcon = 'fa-bar-chart';
    this.titleSufixKey = 'reports';
}

performFilter(filterBy: any) {
    filterBy = filterBy.target.value;
    return this.reports.filter((report) =>
        report.header.toLocaleLowerCase().includes(filterBy)
    );
}

How do I make an alert box’s input change the value in localstorage?

I’m trying to make a bookmarklet that modifies the “local storage” for a game online, but I want it to question the user the amount of “coins” the user wants via an alert.

This is the code

localStorage.setItem('mjs-drift-boss-game-v1.0.1-dailyreward',
 '{"sound":0.7,"music":0,"score":-3,"hasShownTutorial":true,"collectedCoin":999999,"cars":[0,1,2,3,4,5,6,7],"currentCar":7,"currentTip":0,"booster1":99999999,"booster2":9999999,"booster3":999999,"ko":0,"hasShownBoosterTutorial":true}')
alert('Modifed Game!')
location.reload();

How to use deferLoading if we don’t know the total amount of entries in the database?

I am currently working on a project, where I display every virtual machines available on Azure. As there is a lot of data, I would like to use deferLoading from DataTable. The thing is, either I use deferLoading with integer value, or array value, in both cases, I don’t know what is the total amount of entries in the database (the database is sometimes updated, and the total amount of entries subject to change).

So I am wondering how could I handle this ?

While waiting to find a solution using deferLoading, I am also trying to change de drawCallback option, to change the function called when clicking the “Next” or “Previous” buttons. So I would only load 25 new entries in the datable, which would replace the data already present in the datatable.

Another way to solve my problem is to use a static table, but I won’t have all the possibilities that a DataTable can offer.

Here is the current JavaScript code :

$('#table').DataTable({
    pageLength: 25,
    /*
            
    processing: true,
    serverSide: true,
    deferLoading: [25, x],
            
    */
    drawCallback: function() {
        // .off() disables the regular action of #table_<name> button
        // so the program will only execute the function we want.
        $("#table_next").off().click(function(event) {
            showNextVMs();
        });
        $("#table_previous").off().click(function(event) {
            showPreviousVMs();
        });
    }
});

Do not hesitate to share any advice, I never used DataTables before, I may miss some good practices.

Date { NaN } React Native

I’m using react native and I’m trying to convert my timestamp data to date but the output said “Date { NaN }”

       const [eventData1, setEventData1] = useState({});
        
          useEffect(() => {
            database()
              .ref('path')
              .on('value', snapshot => {
                if (snapshot.val() !== null) {
                  setEventData1({...snapshot.val()});
                } else {
                  setEventData1({});
                }
              });
        
            return () => {
              setEventData1([]);
            };
          }, []);
    
     const dates = Object.keys(eventData1).map(
        id => eventData1[id].start_DATE * 1000,
      );
      const sDate = new Date(dates);

Outputs

    console.log(eventData1) -----> //[1648703685000, 1648623600000]//
    
    console.log(sDate) ------> //Date { NaN }//