My JQurery-AJAX code in my Django project for displaying a default value in a calculation based field fails to do so?

These are two of few models in my project:

class Package(models.Model):
    patient=models.ForeignKey(Patient, on_delete=CASCADE)
    diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE)
    treatment=models.ForeignKey(Treatment, on_delete=CASCADE)
    patient_type=models.ForeignKey(PatientType, on_delete=CASCADE)
    date_of_admission=models.DateField(default=None)
    max_fractions=models.IntegerField(default=None)
    total_package=models.DecimalField(max_digits=10, decimal_places=2)
    package_date=models.DateTimeField(auto_now_add=True)

class Receivables(models.Model):
    patient=models.ForeignKey(Patient, on_delete=CASCADE)
    rt_number=models.CharField(max_length=15)
    discount=models.DecimalField(max_digits=9, decimal_places=2, default=0)
    approved_package=models.DecimalField(max_digits=10, decimal_places=2)
    approval_date=models.DateField(default=None)
    proposed_fractions=models.IntegerField()
    done_fractions=models.IntegerField()
    base_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True)
    expected_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True)
    receivables_date=models.DateTimeField(auto_now_add=True)

I needed the approved_package in Receivables to display a default value calculated by subtracting discount from the total_package in Package. And it should all be in real time. So I wrote an AJAX code in Jquery in an HTML file and included the file in my main template. The code looks like:

<script>
    $('select').change(function () {
     var optionSelected = $(this).find("option:selected");
     var valueSelected  = optionSelected.val();
     var textSelected   = optionSelected.text();
     var csr = $("input[name=csrfmiddlewaretoken]").val();
     console.log(textSelected);
        pkg={patient:textSelected, csrfmiddlewaretoken:csr}
        $.ajax({
            url:"{% url 'pt_name' %}",
            method: "POST",
            data: pkg,
            dataType: "json",
            success: function(data){
                console.log(data);
                console.log(data.pkg);
                console.log(data.ptt);
                var tp=data.pkg;
                var ptt=data.ptt;
                $('#id_discount').change(function(){
                    console.log('tp value: ', tp);
                    console.log('ptt value: ', ptt);
                    var discount=document.getElementById('id_discount').value;
                    console.log('discount value: ', discount);
                    var approved_package=document.getElementById('id_approved_package').value;
                    if (ptt=='CASH')
                    approved_package=tp-discount;
                    console.log('approved package new value: ', approved_package);
                });
            }
        });
    });
</script>

The code runs fine in the console of the browser. It fires all the codes. It calculates the approved_package but the result still does not show up in the field as a default value when I enter the discount value. What is wrong with my code? Can someone point it out?

Is the following form of functional components valid?

Pretty new to React here. Thus far, I’ve only been using components that either take no arguments or props. Then, I always render the component using the form <SomeComponent {...props}/>

However, I came across a situation where I didn’t even realize that some of the functions I was creating were actually functional components since they were returning JSX. However, they were visibly different from the way I’m used to making and using components. It looked something like this:

  const MoneyExample = (category, amount) => {
    if (typeof amount !== "number" || typeof category !== "string") {
      return;
    }
    return (
      formatter.format(amount) !== "$0" && (
        <>
          <h4>{category.charAt(0).toUpperCase() + category.slice(1)}</h4>
          <p>{formatter.format(amount)}</p>
        </>
      )
    );
  };

and then rendering it inside another component using like this

{MoneyExample("Budget", someAmount)}

instead of the more common form

<MoneyExample budget={"Budget"} amount={someAmount} />

I’ve tried looking around for info, but I’m not even really sure how to phrase the question. Is this type of thing against React’s principles or completely fine? Sorry if this is obvious to some.

Javascript source missing in the page at first loading

I have an Html page executed in an Iframe where at first loading, sometimes in the source I see that js code is missing at all including the opening js script tag: <script language="Javascript>" but more surprisingly (at least to me), I have links like: href="javascript:namefunction where the string javascript:namefunction is missing too. Is this javascript:namefunction missing part connected to the wrong js loading in the page?
I tried to understand the possible reasons but could not figure out.

How to use addEventListener on multiple input fields to invoke keyup event on them in JavaScript?

I have multiple input fields on which I want to apply onkeyup event on all of them with passing ID of textbox as a parameter. I want multiple keyup event because I want to handle some calculations on the basis of input ID. I tried but failed. Please suggest some solutions.

function GetDynamicTextBox(value) {
    return '<td class="">'+'<select class="js-example-placeholder-single js-states form-control" id="lcompanyselect" onchange="getDriverAndTruck()";>{OptionsPlaceholder}</select>'
                        +'<input type="button" value="+" class="qty-plus" data-toggle="modal" data-target="#edit_co"></td>'
                        +'<td><select class="js-example-placeholder-single js-states form-control" id="ldriverselect"></select>'
                        +'<input type="button" value="+" class="qty-plus" data-toggle="modal" data-target="#edit_driver"></td>'
                        +'<td class=""><select class="js-example-placeholder-single js-states form-control" id="ltruckselect"></select>'
                        +'<input type="button" value="+" class="qty-plus" data-toggle="modal" data-target="#edit_truck"></td>'
                        + '<td><input name = "tripnumber" type="text" class="form-control" id="ltripnumber"/></td>'
                        +'<td><select id="lsubtrip" name="subtrip" class="js-example-placeholder-single js-states form-control"><option disabled selected></option>'
                        +'<option value="1">1</option><option value="2">2</option><option value="3">3</option></select>'
                        + '<td><input name = "date" type="date" class="form-control" id="ldate"/></td>'
                        + '<td><input name = "pickupcity" type="date" class="form-control" id="lpickupcity"/></td>'
                        + '<td><input name = "pickupstate" type="date" class="form-control" id="lpickupstate"/></td>'
                        + '<td><input name = "deliverydate" type="date" class="form-control" id="ldeliverydate"/></td>'
                        + '<td><input name = "delivercity" type="text" class="form-control" id="ldelivercity"/></td>'
                        + '<td><input name = "deliverstate" type="text" class="form-control" id="ldeliverstate"/></td>'
                        + '<td><input name = "loadnumber" type="text" class="form-control" id="lloadnumber"/></td>'
                        + '<td><input name = "loadrate" type="text" class="form-control" id="lloadrate" /><span id="lerrormessage"></span></td>'
                        + '<td><input name = "dispatchfee" type="text" class="form-control" id="ldispatchfee" readonly/></td>'
                        + '<td><input name = "fuel" type="text" class="form-control" id="lfuel"/></td>'
                        + '<td><input name = "cardfee" type="text" class="form-control" id="lcardfee"/></td>'
                        + '<td><input name = "onloadrepair" type="text" class="form-control" id="lonloadrepair"/></td>'
                        + '<td><input name = "shoprepair" type="text" class="form-control" id="lshoprepair"/></td>'
                        + '<td><input name = "trailerrent" type="text" class="form-control" id="ltrailerrent"/></td>'
                        + '<td><input name = "comcheck" type="text" class="form-control" id="lcomcheck"/></td>'
                        + '<td><input name = "advance" type="text" class="form-control" id="ladvance"/></td>'
                        + '<td><input name = "miscellenous" type="text" class="form-control" id="lmiscellenous"/></td>'
                        + '<td><input name = "misc1" type="text" class="form-control" id="lmisc1"/></td>'
                        + '<td><input name = "misc2" type="text" class="form-control" id="lmisc2"/></td>'
                        + '<td><input name = "misc3" type="text" class="form-control" id="lmisc3"/></td>'
                        + '<td><input name = "misc4" type="text" class="form-control" id="lmisc4"/></td>'
                        + '<td><input name = "total" type="text" class="form-control" id="ltotal" readonly/></td>'
                        + '<td><input name = "layover" type="text" class="form-control" id="llayover"/></td>'
                        + '<td><input name = "addtl1" type="text" class="form-control" id="laddtl1"/></td>'
                        + '<td><input name = "addtl2" type="text" class="form-control" id="laddtl2"/></td>'
                        + '<td><input name = "addtl3" type="text" class="form-control" id="laddtl3"/></td>'
                        + '<td><input name = "subtotal" type="text" class="form-control" id="lsubtotal" readonly/></td>'
                        + '<td><input name = "paymentmode" type="text" class="form-control" id="lpaymentmode"/></td>'
                        + '<td><input name = "pay" type="text" class="form-control" id="lpay"/></td>'
                        + '<td><input name = "notes" type="text" class="form-control" id="lnotes"/></td>'
                        + '<td><input name = "grandtotal" type="text" class="form-control" id="lgrandtotal" readonly/></td>'
                        + '<td><button type="button" class="btn btn-outline-info text-info" onclick="savetriplist();">Submit</button>' 
                        +'<button type="button" class="btn btn-outline-danger text-danger remove">Remove</button></td>'
            }

Use Express post request to emit Socket.io

I want get username when user post it, but io.sockets.emit is not working. However, When i didn’t put io.sockets.emit on app.post, It is working.

my html

<html>
    <body>
        <form action="chat" id="main" method="post">
            <div>
                <input type="text" id="id" name="username" value="" placeholder=" " required />
                <label for="id">暱稱</label>
            </div>
            <div>
                <input type="text" id="key" name="key" value="" placeholder=" " />
                <label for="key">房號</label>
            </div>
            <button type="submit" value="加入房間" class="btn">加入房間</button>
        </form>
    </body>
</html>

my js

io.on('connection', (socket) => {

    socket.on('joinRoom', username => {
        console.log(username);
        console.log("joinRoom");
    });
    socket.on('chat message', msg => {
        const user = getCurrentUser(socket.id);
        console.log(user);
        io.emit('chat message',  msg);
  });
});
app.post('/chat', urlencodedParser, function (req, res) {
    io.sockets.emit('joinRoom', "aa")
    console.log(req.body)
    res.sendFile('public/chat.html', { root: __dirname })
});

‘joinRoom’ seems not receive anything.

join value FormData with axios use javascript

i send value using postman with body form data format like this :

example with postman

analisa_type:1;1;2
eficiency_type:0;1;1

I input array data with separator (;)

i am confused how to separate it on axios
this is my code

let eficiency_name = this.items_efiicieny.map(x => x.analisa_exception_label).join(";");
let eficiency_type = this.combine.map(x => x.object_type).join(";");

const f = new FormData();
f.append("analisa_type", eficiency_name);
f.append("label_type", eficiency_type);

how to format the form data so that the value is like in postman?

Map inside map value

I tried show for each item in data array only the name key I need to show it with table.

const data = [{id: "111", name: "Danny", city: "NYC"},
              {id: "222", name: "Roni", city: "LDN}, 
              {id: "333", name: "Suzi", city: "TLV",
              {id: "444", name: "John", city: "SF"}
             ]
const config = [{fieldToShow: "name"}]


  <tbody>
  {data.map((row) => {
    return (
      <tr>
        {config.map((value) => {
          return <td>{row[value.field]}</td>;
        })}
      </tr>
    );
  })}

but it not work …

Displaying selected options in custom multiselect dropdwown as tags – React

I’ve custom multiselect dropdown which is implemented as given below

const RequestExpertSupport = function Basic({ data, onSelectedItemsChanged, selectedItemsIndices }) {

        const props = {

            "data" : [

                "My account and profile",

                "Understanding my footprint",

                "Target setting",

                "Specific actions",

                "Creating a plan",

                "Finance, funding and grants ",

                "Using the Carbon Planner platform",

                "Other",

            ],

            "selectedItemsIndices": [],

        }

        //

        const handleSelectedItemsChanged = useCallback(

            selectedItemsIndices => {

                onSelectedItemsChanged(selectedItemsIndices)

            },

            [onSelectedItemsChanged]

        );

       function onSelectedItemsChanged(selectedItemsIndices) {

            // let arrTopic = [];

            // const selected = document.querySelectorAll('#multiSelectDrop:checked');

            // const values = Array.from(selected).map(el => el.value);

         

            // console.log(values);

            console.log(selectedItemsIndices);

        }

        function renderItem (datum, index) {

                                return (

                                                <span>

                                                                {datum}

                                                </span>

                                );

                }

   

        return(

            <RequestExpertSupportDiv>

                <div className="container">

                    <div className="formContainer">

                        <form>

                            <label className="helpLabel">What would you like help with?</label>

                            <DropdownListTrigger

                                dropdownList={

                                    <MultiSelectDropdownList

                                        id="multiSelectDrop"

                                        data={props.data}

                                        onSelectedItemsChanged={handleSelectedItemsChanged}

                                        renderItem={renderItem}

                                        selectedItemsIndices={selectedItemsIndices}

                                    />

                                }

                                position="right"

                                className="ddlFilter"

                                >

                                <button className="zb-button zb-button-secondary zb-button-with-icon-after">

                                    <Span>Choose topic(s)</Span>

                                    <Icon

                                        name="chev-down-xsmall"

                                        style={{

                                            verticalAlign: "text-bottom",

                                        }}

                                        title={null}

                                    />

                                </button>

                            </DropdownListTrigger>

                            <div className="selectedTopics">

                                Selected topics are:

                            </div>

                            <label className="tellUsLabel">What would you like help with?</label>

                            <textarea name="helpReview" rows="4" cols="43" className="textArea"

                                style={{ width: "410px", height: "290px", marginTop: "2%" }}

                                placeholder="Type your message here ..."></textarea>

                            <button className="sendBtn" name="sendBtn">Send</button>

                       </form>

                    </div>

                </div>

            </RequestExpertSupportDiv>

        );

    };

    export default RequestExpertSupport;  

This code fetches the indices of selected options in Multiselect dropdown.

function onSelectedItemsChanged(selectedItemsIndices) {

        // let arrTopic = [];

        // const selected = document.querySelectorAll('#multiSelectDrop:checked');

        // const values = Array.from(selected).map(el => el.value);

     

        // console.log(values);

        console.log(selectedItemsIndices);

    }    

Console is given below:
console
Now I want to display those selected options as tags like this:
tags
This is the code for tags:

<Div

                    flex="flex"

                    display="inline-flex"

                    height="36px"

                    borderWidth="1px solid #009FAC"

                    borderRadius="3px"

                    backgroundColor="#def8fa"

                    justifyContent="space-around"

                    alignItems="center"

                    marginRight="10px"

                    marginBottom="10px"

                    key={index}

                    style={{ minWidth: "92px", maxWidth: "175px" }}

                  >

                    <Span

                      padding="0px"

                      fontSize="14px"

                      lineHeight="20px"

                      fontWeight="400"

                      marginLeft="5px"

                      marginRight="5px"

                      style={{ maxWidth: "142px" }}

                    >

                      // need to put selected options here

                    </Span>

                    <Icon

                      name="close-inverted-small"

                      onClick={(event) => removeSelectedTopic(event, topicId)}

                    />

                    &nbsp;

                  </Div>  

I’m not getting how to link function SelectedItemsChanged(selectedItemsIndices) with that tags frontend code to dosplay selected options as tags…

how to change the text of Alert box button

I want to change the “OK” text button to another thing like “Agree” but I don’t know how to do it, Would you guys help me?

here is my code:

function notification() {
    let isConfirm = window.confirm("any");

    if (isConfirm) {
        console.log("any");
    } else {
        console.log("any");
    }
}

notification();

How to update a key/value pair in a nested array of objects in Javascript

this is my data structure:

[
    0:
        key1: value,
        key2: value,
        array:
            0:
                thisId: xxxxx,
                thisValue: value,
            1:
                notThisId: someId,
                notThisValue: value,
        key3: value
    1:
        key1: value
        key2: value
        array:
            0:
                anotherId: id
                anotherValue: value
        key3: value
]

Hello, I have a query with is returning:

thisIdRef: xxxxx, 
thisNewValue: newValue

Is it possible to update the nested ‘thisValue’ to ‘thisNewValue’ where ‘thisIdRef’ is equal to ‘thisId’, or ‘xxxxx’?

I have done something similar below using findIndex and splice, but this is for a non-nested key/value pair and I can’t work out how to find a nested id, or indeed if it’s possible.

let newArray = oldArray;
const index = newArray.findIndex(post => post._id === editedPostId)
newArray.splice(index, 1, {
    ...newArray[index],
    post: editedContent
})

Any help very much appreciated.

Google pay button design in react native without libraries

I’m implementing Google pay to my react native app. I have to create the google pay button with the native assets provided by google, since i’m using the react native payments but they don’t have the already built in button, i’m confused to how can i use their assets to create the button. they mentioned in their site that we have to put drawable, layout and values in android/app/main/res folder. But i don’t understand what to do after that. and i’m getting an error when building. Can anyone please give me an example or an article where can i read about that. I searched but i didn’t find any article or tutorial about that.

Error: Objects are not valid as a React child (found: object with keys {username}) [duplicate]

In my ReactJS application I have been trying to solve this problem for a very long time.

In a Users.js file Im fetching all the users from the database and storing it in a state called user. My goal is to render all these users by iterating through the list of users.

Here is my list of users that im getting from my backend:
list of users to be displayed

Then I am running a loop in the Users.js component and for every user, im rendering a User component

Here is my Users.js component:

import React, { useEffect, useState } from "react";
import User from "./User/User";

export default function Users() {
   const [users, setUsers] = useState([]);
   useEffect(() => {
       axios
           .get("http://localhost:8000/users")
           .then((res) => {
               console.log(res.data);
               setUsers(res.data);
           })
           .catch((err) => console.log(err));
   }, []);
   return (
       <div className="container">
           {users.map((user) => {
               console.log(user);
               return <User key={user.id} username={user.username} />;
           })}
       </div>
   );
}

here is my User.js component:

import React from "react";
import { Link } from "react-router-dom";

export default function User(props) {
    console.log("User.js component.");
    console.log(props.username);
    return (
        <div>
            <div className="card">
                <Link to="/">
                    <div className="card-body">
                        Use this kinda element to show user: {props}
                    </div>
                </Link>
            </div>
        </div>
    );
}

I expected everything to run properly but I got this error:

error

I researched a little bit about the error and found out that it is because im passing an object as a prop to a component. But when I checked the typeof user.id and typeof user.username which i was passing as a prop to the User component. I found that none of them (user.id and user.username) were objects. They were number and string respectively.

Please help me solve this.

Thanks!

How to get Scrollbar for left side of the Image/Div after it is scaled at the center

I’m centering an image using display:flex & justify-content:center
and using some zoom buttons to scale the image when they’re clicked.

The issue is that I’m not able to get a scroll bar to go to the Left Side of the image after it is scaled.

I checked about the scaling property and learned that it scales the (0,0) coordinates and possibly I’m trying to go the negative coordinates (https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/scale()#scaling_the_x_and_y_dimensions_together)

Is there anything i can do to go to have full access of the image after it is being scaled? (by full access i mean to the left/right/top/bottom)
Here is the fiddle for reference : https://jsfiddle.net/r9sdhjyz/1/