Javascript onclick how to undo when clicked again

I’m creating a filter to search for your perfect shoe’s by answering questions. Right now I’ve got a couple of questions, each with multiple answers. By clicking on an answer a variable gets edited with the data of the value of that answer. The problemm is that you can click on the variable as many times as you like and the value will keep being added. Is there a way to change the color of the answer button when clicked and when clicked again it undo’s adding the value to the variable and changes the color back?

Code:

<div class="container">
    <div id="question"></div>
    <div id="answer"></div>
    <button onclick="check()" id="nextbtn">Next</button>
    <div id="finalLink"></div>      
</div>
<script type="text/javascript">

    var ShoeTest = [
        [
            'Whats your size?',
            ['41', '41'],
            ['42', '42'],
            ['43', '43']
        ],
        [
            'What color would you like?',
            ['Red', 'red'],
            ['Blue', 'blue'],
            ['Yellow', 'yellow'],
            ['Green', 'green']
        ],
        [
            'What brand would you like?',
            ['Adidas', 'adidas'],
            ['Nike', 'nike'],
            ['Puma', 'puma']
        ]
    ];

    let parms = [];

    count = 1;
    var questionNumber = 0;
    var button = document.getElementById('answer');
    var question = document.getElementById('question');
    var answerButton;
    var flag = true;

    function getLink(parms) {
        return ""+parms.join("&")
      };

      button.addEventListener("click",function(e) {
        const tgt = e.target;
        parms.push(tgt.value);
        console.log(getLink(parms))
      })

    function check(){
        oldAnswerButton = document.querySelectorAll('.filter_anwser');
        oldQuestion = document.getElementById('question');
        for(let z = 0; z < oldAnswerButton.length; z++){
            oldAnswerButton[z].style.display = 'none';
        }
        //question 
        for (let y = 1; y < ShoeTest[questionNumber].length; y++){
            // button
            var btn = document.createElement('button');
            btn.value = ShoeTest[questionNumber][y][1];
            btn.className = "filter_anwser";
            btn.textContent = ShoeTest[questionNumber][y][0];
            btn.setAttribute('data-el', 1);
            btn.onclick = ButtonColor();
            button.appendChild(btn);
            // class
            answerButton = document.querySelectorAll('.filter_anwser');
        }
        // question
        question.textContent = ShoeTest[questionNumber][0];
        question.id = "questionID";
                
        console.log(".....");
        // adds 1 to question to see a different question
        questionNumber++;
    }

    function ButtonColor(){
        btn = document.getElementById('answer');
        btn.style.backgroundcolor = flag ? "unclicked" : "clicked"
       flag = !flag;
    }

Also if you have multiple answers of one questions add a , between instead of a &?

Failure to get response from POST jQeury [duplicate]

So I got a quick script working with HTML and JS, but I can’t for the love of me get the response from the POST request. Here is what I have currently have:

<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="something()">Click Me!</button>
<script>
function something(){
  const Url = 'https://somelink.com';
  const date = 'somedata'
  var V
  
  $.post(Url,date,function(data) {
  V = data
  });
  
  alert(V)
}
</script>
</body>
</html>

I did try having the alert in the function(data) part but it would not register for some exact reason so I moved it out. Now it registers the alert but it can not get the response from the request.

I am testing it in JS Fiddle and the console log is “50:9 Uncaught ReferenceError: V is not defined”. Any and all help/nudges will be greatly appreciated. My goal is to get the response from the request and use it further down the line, so I am just testing as a proof of concept/correct coding with the alert.

React – history push throwing error: Failed to execute ‘pushState’ on ‘History’

I have a page on the URL:http://localhost:10001/track/8311c15a-7f7f-47ff-b81a-6f6904ad191c/my-form where I have a form. After the form is submitted I am using react’s router history to redirect to a success page

const MyComponent = ({match, location, history}: RouteComponentProps

const onSubmit = () => {
  history.push(`/${baseUrl}/success`)
}

But, when I try to do so, I get an error:

Uncaught DOMException: Failed to execute 'pushState' on 'History': A history state object with URL 'http://track/8311c15a-7f7f-47ff-b81a-6f6904ad191c/success' cannot be created in a document with origin 'http://localhost:10001' and URL 'http://localhost:10001/track/8311c15a-7f7f-47ff-b81a-6f6904ad191c/my-form'.

It is the first time I have encountered this error. What am I doing wrong here?

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.