React.Js how to display price based on dropdown selection?

I really need help, I’m stuck on this matter for over 2 days and so far nobody was able to help me.

I’m trying to do one thing only: I have an e-commerce shop where there’s multiple items. Each item can have multiple options like quantity: 300g, 500g and 1000g. I want to display the price of that item based on the quantity that’s selected. I have all the data in my own API. Here’s a photo so you can clearly see what I’m trying to do:

enter image description here

and here’s some relevant code.

1) How each item looks like in my json file:

{
            id: '233fdcc3',
            nume: 'Adimel',
            slug: 'adimel',
            categorie: 'ingrasaminte',
            imagine: 'https://images.unsplash.com/photo-1609361528183-1acc0d399845?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=687&q=80',
            pret: [
                {'300g': 25.00},
                {'500g': 32.00},
                {'1000g': 44.00},
            ],
            descriere: 'lorem ipsum blaboajsojas saf sfa fas fasfgaiasfagagjgoajg afaoj foasf jafo afo afdgagagdg a a',
            inStoc: 5,
            reducere: '10%',
},

^ As you can see above, “pret” is an array that contains key value pairs.

Then, here’s my product page code:

I have set useState because I’m assuming price always changes based on the selection like this:

const [currentProductPrice, setCurrentProductPrice] = useState('');

and then part of my component code is here(I highlighted the part that I had no idea how to do)

<QuantityInput name='cantitate' onChange={handleChange}>
                    {product.pret.map(valoare => (
                        <Optiune key={Math.random(10)} value={Object.keys(valoare)}>{Object.keys(valoare)}</Optiune>
                    ))}
                    
                </QuantityInput>
            </QuantitySelector>
            <TotalPriceAndQuantity>
                <TotalPrice>
                    Total: 
                    {???????}
                    </TotalPrice>

I’ve also made a function like this

const handleChange = (e) => {
console.log(e.target.value);

}

and it works perfectly, i only get the keys, but how do I set the price based on the key selected?

HUGE thanks in advance!

Replace certain character inside multiple/all instances of an href attribute with javasacript?

I’m trying to change the character “å” into “aa” inside the href attribute of a bunch of links.

Example of what i have now:

<a id="edittoaa" href="/på-landet">På landet</a>
<a id="edittoaa" href="/i-landet">I landet</a>
<a id="edittoaa" href="/i-landet">I landet</a>
<a id="edittoaa" href="/på-landet">På landet</a>
<a id="edittoaa" href="/på-landet">På landet</a>
<a id="edittoaa" href="/i-landet">I landet</a>
<a id="edittoaa" href="/på-landet">På landet</a>

Example of how i want it to look after js has done it’s magic:

<a id="edittoaa" href="/paa-landet">På landet</a>
<a id="edittoaa" href="/i-landet">I landet</a>
<a id="edittoaa" href="/i-landet">I landet</a>
<a id="edittoaa" href="/paa-landet">På landet</a>
<a id="edittoaa" href="/paa-landet">På landet</a>
<a id="edittoaa" href="/i-landet">I landet</a>
<a id="edittoaa" href="/paa-landet">På landet</a>

Basically all instances of “å” have been changed into “aa” inside the href attribute (please note: kept untouched in the link text “På landet”).

I tried some different code while tampering about in jsfiddle, but i can’t seem to crack it. Only time i came “close”, was by modifying this piece – which is overkill as it formats the link in additional ways as well, and and only affects one instance of the link, instead of them all which i’m looking for. But it changes the “å” into a “aa” at least.

var str = document.getElementById("edittoaa").getAttribute("href");

var lastitem = str.split("/").pop(); //taking out last item after slash 

lastitem = lastitem.split( "å" ).map( function(value){ return value.replace(/[*()&/]/g, '').toLowerCase() } ).join( "aa" );    //removing special characters and replacing space with hyphen

str = str.substring(0, str.lastIndexOf(".")) + lastitem;

document.getElementById('edittoaa').setAttribute("href",str);
<li><a id="edittoaa" href="/boliger/på-landet">Link</a></li>
<li><a id="edittoaa" href="/boliger/på-landet">Link</a></li>
<li><a id="edittoaa" href="/boliger/på-landet">Link</a></li>

changing description onmouseover

I am trying to build a site where I have a table filled with images (“items”) on the main body, and
a div where the description is supposed to go, and I want it so when you hover the mouse over the items, the description shows in the “sidebox” div.

Removing a matching string item from a multidimensional array

I have a multi dimensional array derived from checkbox values, they can have the same strings for all instances of the outer array.

Example Array:

[
    ['One', 'Two', 'Three'],
    ['One', 'Two', 'Three'],
    ['One', 'Two', 'Three'],
]

When I call the function, I am passing an index number which represents which one of the inner arrays I want to address. For instance, if the user unchecked the checkbox representing ‘Two’ in the 1 index, I’d want the multi dimensional array to change to this.

 [
        ['One', 'Two', 'Three'],
        ['One', 'Three'],
        ['One', 'Two', 'Three'],
 ]

I am having trouble writing this function. This is in React and the snippet to address this is currently like this:

setCheckedValues(prevArray => {
          const newItemArray = prevArray.slice()
          const newItemArrayFiltered = [...newItemArray, newItemArray[index].filter(name => name !== event.target.name)]
          return newItemArrayFiltered
        })

I’ve searched a lot and am stuck as to how to remove a string in only one of the inner arrays. Thanks for any assistance!

How to properly catch fetch request in django

I started studying django.

I have js code that calls fetch when I click the button

button = document.querySelector('.button')
button.addEventListener('click', function(){
    fetch('http://127.0.0.1:8000/test_fetch/',
{   
    method: 'GET',
    headers: {
        'Content-Type': 'application/json',
        "X-Requested-With": "XMLHttpRequest",
        "HTTP_X_REQUESTED_WITH": "XMLHttpRequest"
    }
})
})

<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button class="button">hello</button>
   
    {{ ajax }}
    <script src="{% static 'train_app/js/test_fetch.js' %}"></script>
</body>
class TestFetch(TemplateView):
    template_name = 'train_app/test_fetch.html'
    
    def get(self, request):
        ajax = request.headers
        data = {
            'name': 'Yura',
            'age': 20,
            'list': [1,2,3,4], 
            'ajax': ajax
        }
        
            
        return render(request, self.template_name, context=data)

I tried to catch the fetch request using request.META and request.headers. But they return to me information only about the first get request which is caused through urls.py.

How do I get information that this was a fetch request and its Content-Type attribute.

How to tell if an element accepts keyboard input?

I’m working on keyboard shortcuts for a web application and need to check if a keypress should trigger the shortcut or if it is just the user typing and should therefore not trigger the shortcut.

For example, a common pattern is to use the / or s keys to open the global search bar. Obviously this should not open the search bar if the user is typing into another input.

The ideal logic would go something like this: On keypress, check the currently focused element. If the element accepts keyboard input (can be typed into), then do nothing. If the element does not accept keyboard input, run the shortcut.

Here’s what I have so far:

function acceptsKeyboardInput(element) {
    return (
        element.tagName === "INPUT" ||
        element.tagName === "TEXTAREA" ||
        element.isContentEditable
    );
}

Does this approach catch every case or is there a better way to tell if an HTML element accepts keyboard input?

Testing whether a path in a directed graph does not cause cycles

This is a different question from what I have found so far related to cycles in graph as they relate to finding cycles in general but I need to find a cycle in a specific situation.

Consider the following graph:

n1: [n2]
n2: [n3]
n3: [n4]
n4: [n5, n2]
n5: []

This function should only return true when testing for the path from n4 to n2.
In my situation I don’t consider a cycle other paths because they are “safe” to render in the UI. However, if I would try to render the association between in n4 to n2 I would recreate the whole path recursively.

So far I came up with the following:

/**
 * @param {string} target The target node
 * @param {Record<string, string[]>} g The graph
 * @param {string} key The current key
 * @returns {boolean} true when going from `key` to `target` would create a cycle.
 */
hasCycle(target, g, key) {
  if (target === key) {
    return true;
  }
  
  const neighbors: string[] = [];
  Object.keys(g).forEach(prop => {
    if (g[prop].includes(key)) {
      neighbors.push(prop);
    }
  });
  
  for (const neighbor of neighbors) {
    if (neighbor === key) {
      return true;
    }
    if (hasCycle(target, g, neighbor)) {
      return true;
    }
  }
  return false;
}

This works in most cases except for the following:

n1: [n2]
n2: [n3]
n3: [n2]

When I test hasCycle('n2', {...}, 'n3') this function returns true as the cycle exist but for the purpose of the UI I am building I am not consider it a cycle just yet (I would if I would be testing for n3 -> n2).

Sequelize: Optional limit parameter

I’ve seen a few questions on optional where clauses and order params, both of which I can implement, but I was wondering how to have an optional limit parameter? Maybe I’m missing something easy, but I can’t see anything obvious in the docs

If I specify it like this:

const limit = req.query.limit;
Example.findAll({ 
  limit: limit
})

how can I omit limit in certain situations?

JavaScript, convert repetitive task into recursion

Does anyone know how I can convert multiple for loops with if-else statements into a recursive function?

What the code does is it takes an object of meta tags and then checks all metatags in that object. If one of them has an object of meta tags inside it, it takes it and checks if there’s also an object of metatags inside it.

So it’s a chain of meta tags, all nested inside each other. I know it’s confusing.


for (const [key, value] of Object.entries(dataSet.elements)) {
              // we go over every value and remove it if it's not in the whitelist.
              if (elements.includes(key) === false ){
                let element = dataSet.elements[key];
                // some metatags have metatags inside of them, and we have no option except to check and delete them
                if (element.hasOwnProperty('items') && typeof element !== "undefined"){
                  for (const [key, value] of Object.entries(element.items)) {
                    let sequence = value.dataSet.elements
                    for (const [key, value] of Object.entries(sequence)) {
                      let elementInSequence = sequence[key]
                      // check if there are metatags inside of metatags inside of metatags.
                      if (elementInSequence.hasOwnProperty('items') && typeof elementInSequence !== "undefined"){
                        for (const [key, value] of Object.entries(elementInSequence.items)){
                          let sequenceInSequence = value.dataSet.elements
                          for (const [key, value] of Object.entries(sequenceInSequence)){
                            let elementInSequenceInSequence = sequenceInSequence[key]
                            if (typeof elementInSequenceInSequence !== "undefined"){
                            for (let i = 0; i < elementInSequenceInSequence.length; i++) {
                              dataSet.byteArray[elementInSequenceInSequence.dataOffset + i] = 0;
                            }
                          }}
                        }     
                      }
                      else if(typeof elementInSequence !== "undefined"){
                        for (let i = 0; i < elementInSequence.length; i++){
                          dataSet.byteArray[elementInSequence.dataOffset + i] = 0;
                        }
                      }
                }}}
                else if (typeof element !== "undefined") {
                  for (let i = 0; i < element.length; i++) {
                    dataSet.byteArray[element.dataOffset + i] = 0;
                    }}}
               // if the value is in our whitelist, skip it.     
              else if(elements.includes(key) === true){
               console.log(key + " whitelisted, skipping.")
             }}

Implement koa-router to handle optional parameter with whereIn condition

I have section based routing system with some common functions. And an overall routing system to handle different stuff.

Section routes look like this.

router.get('/api/marketing/get_campaigns_list', campaignController.getCampaignsList);
router.get('/api/design/get_campaigns_list', campaignController.getCampaignsList);
router.get('/api/content/get_campaigns_list', campaignController.getCampaignsList);

And some other routes look like this…

router.get('/api/analytics/something_else', analyticsController.somethingElse);

I want to club my common routes to clean code, something like

router.use('/api/:section', middleware, campaignController.routes());

But it catches all the request goes through the middleware which has authentication logic.

How can I define the router such that it will only run for some particular optional params, for example, something like this as done in React.

router.use('/api/:section(content|marketing|design)', middleware, campaignController.routes());

JS switch statements

What I am trying to create is to have a Dropdown-list which allows a user to choose from and whatever is chosen should be written into a cell in the table. I have written the following code but it seems to be not working:

var firstPlay = document.getElementById("all_options").value;

function myFunction() {

  switch (firstPlay) {

    case "Option1":
      document.getElementById("1").innerHTML = "Option1Text1";
      break;

    case "Option2":
      document.getElementById("2").innerHTML = "Option2Tex2";
      break;

    case "Option3":
      document.getElementById("3").innerHTML = "Option3Text3";
      break;

    case "Option4":
      document.getElementById("4").innerHTML = "Option4Text4";
      break;
  }

}
table,
th,
td {
  border: 1px solid black;
}
<form>
  Select one from:<br>
  <select id="all_options">
    <option value="Option1">Option1</option>
    <option value="Option2">Option2</option>
    <option value="Option3">Option3</option>
    <option value="Option4">Option4</option>
  </select>
</form>

<button type="button" onclick="myFunction()">Add to the  table below</button>
<hr>
<table>
  <tr>
    <td id="1">empty</td>
  </tr>

  <tr>
    <td id="2">empty</td>
  </tr>

  <tr>
    <td id="3">empty</td>
  </tr>

  <tr>
    <td id="4">empty</td>
  </tr>
</table>

It seems as only if I choose any option from Dropdown-list the Option1Text1 is going always to be written in the table in the first cell. Is there something wrong with my SWITCH statement that I am using in my code?

How to connect dots is css with js div element with next/prev slider

Hello can Someone help me connect these dots with the div element with js?

<html>
  <link href="./style.css" rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>     
<div class="divs">
    <div class="cls1">
        <div>Yes 1 </div>
        <div>Element 1 </div>
    </div>
    <div class="cls2">
        <div>Yes 2 </div>
        <div>Element 2 </div>
    </div>
    <div class="cls3">
        <div>Yes 3 </div>
        <div>Element 3 </div>
    </div>

</div>
<a id="next">next</a>
<a id="prev">prev</a>

<li class="nav-dots">
    <label class="nav-dot" id="img-dot-1" onclick=""></label>
    <label class="nav-dot" id="img-dot-2"></label>
    <label class="nav-dot" id="img-dot-3"></label>
  </li>

<script>
$(document).ready(function(){
    $(".divs>div").each(function(e) {
        if (e != 0)
          $(this).hide();
    });
    
    $("#next").click(function(){
      const visibleDiv = $(".divs>div:visible");
      const nextDiv = visibleDiv.next();
      if(nextDiv.length > 0) {
        visibleDiv.hide();
        nextDiv.show();
      }

    });

    $("#prev").click(function(){
      const visibleDiv = $(".divs>div:visible");
      const prevDiv = visibleDiv.prev();
      if(prevDiv.length > 0) {
        visibleDiv.hide();
        prevDiv.show();
      }
    });
});

</script>
</html>
.nav-dots {
    width: 100%;
    bottom: 9px;
    height: 11px;
    display: block;
    text-align: center;
}

.nav-dots .nav-dot {
    top: -5px;
    width: 11px;
    height: 11px;
    margin: 0 4px;
    position: relative;
    border-radius: 100%;
    display: inline-block;
    background-color: rgba(37, 37, 37, 0.856);
}

.nav-dots .nav-dot:hover {
    cursor: pointer;
    background-color: rgba(167, 228, 0, 0.8);
}

I want so that I also changed color when on the specific slider and when u click the dots it shows the propper div element. Preview : the plain look

Not sure how to do it, I tried onClick display one but its just ruins it , makes it more a enalbe/disable button rather then a next/prev dot for the specific div element.

unparenthesized unary expression can’t appear on the left-hand side of ‘**’

I am writing a program that has math in it.

According to Mozilla, ** is for exponentiation, and it has lower priority than unary minus (-). Therefore, I would expect -1**2 to mean (-1)**2. However, Firefox says:

Uncaught SyntaxError: unparenthesized unary expression can't appear on the left-hand side of '**'

The Mozilla page says nothing about requiring parentheses between math operators when the documented operator precedence is desired. So why does -1**2 not work?

I understand that the JavaScript precedence is not the same as what Mathematicians use. However, that is not grounds for forcing parentheses that are not required by the specification. The current behavior seems to mean that code written according to the specification might not work?