complex object manipulation

I have an array:

const arr = [
    {
        countries : {countryCode :"US", value: true},
        vendors:  [{vendorName: 'TES', value: true}, {vendorName: 'HPEFS', value: true}]
    },
    {
        countries : {countryCode :"CA", value: true},
        vendors:  [{vendorName: 'TES', value: true}, {vendorName: 'HPEFS', value: false}]
    }
];

expected result:  [{vendor: "TES", countries: [US, CA]}, {vendor: "HPEFS", countries: [US]}]

Any idea is appreciated, Thanks in advance

Handling form content with JavaScript and Perl

I have a music project in Perl which also requires some JavaScript but I seem to be stuck.
I need to execute a program (ffplay) as a command-line application so it runs without displaying a GUI window. The Perl handles the server end of things (sqlite database access). I need JavaScript because I display track names as a button, which when clicked is supposed to run ‘ffplay’ to play the track named in the button code. But the button click requires JavaScript.

When I click a track name button, it only displays the first track, no matter which one I
click.

The following code is in a ‘while’ loop extracting track names from the DB.

print<<EndHTML;
<script>
function process(form) {
    var form=document.Player
        alert ("Track: " + form.Player.Track.value)
}
</script>
EndHTML

print qq{<form name="Player">};
print qq{<input type="button" onClick="process(this.form)" class="alphaButton" name="Track" value="$Track"><br/>};
print qq{</form>};

Google Drive API doesn’t show files inline

I am trying to show a file from the Google Drive API inline so that the browser will display it. So far when I request the file it only downloads it. But when I add some code to make it show it in line I get the error “Failed to load PDF document”.

Here is my code:

const googleFile = new Request(`https://www.googleapis.com/drive/v3/files/${FileID}?alt=media`, {
      method: "GET",
      headers: {
        "Authorization": `Bearer ${googletoken}`,
      },
    });
const googleFileResponse = new Response(fetch(googleFile), {
      headers: {
        'Content-Disposition': 'inline',
      }
    });
    return googleFileResponse

Thanks for your help.

angular asynchronous request from multiple methods

From ngOnchanges I called the method _generateLocationFormForApproval and it has an output which is this.absoluteUri. After calling _generateLocationFormForApproval the next call is _pageEventDealsForApprovalList. Now I want to access the result from _generateLocationFormForApproval whic is this.absoluteUri inside _pageEventDealsForApprovalList after its result but it is giving me undefined although this.absoluteUri has a value.

Any idea ? with the asynchronous call ? Thansk.

#code

  ngOnChanges(changes: SimpleChanges): void {
      if(this.dealId) {
        this._generateLocationFormForApproval();
        this._pageEventDealsForApprovalList();
      }
    }
    
    
    
    private  _generateLocationFormForApproval() {
      this.dealService.generateLocationSubmission(this.dealId)
      .subscribe({
        next: (res) => {
          if (res.isSuccess) {
            this.absoluteUri = res.data.absoluteUri;
          }
        },
        error: err => this.notificationService.showError(err),
        complete: noop,
      });
    }
    
private _pageEventDealsForApprovalList() {
  console.log("1")
  console.log("this.absoluteUrithis.absoluteUri" , this.absoluteUri)
  this.searchInput = '';
  const status = [DEAL.STATUS.FORAPPROVAL, DEAL.STATUS.APPROVED]
  this.dealType = [];
  this.isLoading = true;
  this.dealService
    .getAllDeals(
      status,
      this.accountId,
      this.transaction.id,
      this.table.pageIndex + 1,
      this.table.pageSize,
      this.searchInput,
      this.table.sortParams,
      this.table.sortDirs,
      this.dealType
    )
    .pipe(finalize(() => (this.isLoading = false)))
    .subscribe((res) => {
        if(res) {
          console.log("this.uri" , this.absoluteUri)
        }
    }, (err) => this.notificationService.showError(err)
  );
}

scroll the textarea content and a child div with parent div only in react

I have a child div of line numbers and a textarea inside a parent div. So what I required is only parent div should be scrollable, neither textarea nor child div. Also height of the parent should be fixed to 170px.

enter image description here

Following is Jsx code

      <div
        style={{
          display: 'flex',
          overflowY: 'auto',
          height: '150px',
        }}
      >
        <div style={{ marginRight: '10px' }}>
          {lineNumbers?.map((item: any) => (
            <TextWrapper
              key={item}
              text={`${item}`}
              className={'marginTB2'}
            />
          ))}
        </div>
       
        <textarea
          rows={6}
          value={enteredAdrs}
          onChange={(e) => {
            setEnteredAdrs(e.target.value)
          }}
          onBlur={handleManualData}
          onKeyDown={handleKeyDown}
        /> 
        
      </div>

following is css code

 textarea{
    background-color: #151414;
    color: #fff;
    padding: 0;
    line-height: 157%;
    box-sizing: border-box;
    border: none;
    margin: 0;
    width: 100%;
    resize: none !important;
    height: 100%;
  }

  textarea:focus{
    box-shadow: none !important;
    outline: none;
  }

can i get selected option country from intl-tel-input (PHP EDIT DATA)

I’m new and right now i’m practicing create form with two fields (phone number and country). I’m using intl-tel-input from https://github.com/jackocnr/intl-tel-input and i wonder can i get selected option country using PHP while the data using intl-tel-input. Here’s my HTML & PHP code

<div class="form-group">
    <label for="exampleFormControlInput1">Country of Origin</label>
    <select class="custom-select" id="country" name="country" value="<?=$pecah2['origin_country'] ?>" <?php if($pecah2['origin_country'] = $pecah2['origin_country']){echo 'selected="selected"';} ?>></select>
</div>
<div class="form-group">
    <label for="exampleFormControlInput1">Phone Number</label><br>
    <input type="text" class="form-control" name="phonenumber" id="phone" required value="<?= $pecah2['phone_number'] ?>">
</div>

JS

<script src="https://code.jquery.com/jquery-3.6.0.min.js" type="text/javascript"></script>
<script src="assets/build/js/intlTelInput.js" type="text/javascript"></script>
<script src="assets/build/js/intlTelInput.min.js" type="text/javascript"></script>
<script>
   var input = document.querySelector("#phone");
   var countryData = window.intlTelInputGlobals.getCountryData();
   var addressDropdown = document.querySelector('#client_country');
   var iti = window.intlTelInput(input, {
       utilsScript :'assets/build/js/utils.js'
   });
   for (var i = 0; i < countryData.length; i++){
       var country = countryData[i];
       var optionNode = document.createElement("option");
                        optionNode.value = country.iso2;
       var textNode = document.createTextNode(country.name);
                        optionNode.appendChild(textNode);
                        addressDropdown.appendChild(optionNode);
                       }

      addressDropdown.value = iti.getSelectedCountryData().iso2;
                       
      input.addEventListener('countrychange',function(){
                        addressDropdown.value = iti.getSelectedCountryData().iso2;
                       });

      addressDropdown.addEventListener('change', function(){
                        iti.setCountry(this.value);
                       });
</script>

i’m practicing by different youtube videos by the way

How to update a javascript object keys value using the index of an object

I have an array of object like

const test = [{id: 1, text: "Test"}, { id: 2 , text: "Test 2" } ]
const index =  test.findIndex((listItem) => listItem === test[0])

Here I am trying to update the value of text key using the index.

I have a solution like this:

 const editItemText = (value) => {
    const newList = replaceItemAtIndex(todoList, index, {
      ...item,
      text: value,
    });

    setTodoList(newList);
  };
  
const replaceItemAtIndex =  [...arr.slice(0, index), newValue, ...arr.slice(index + 1)];

is there any other option to do so ? Also How does the given solution works ?

Thanks.

Creating and accessing unique html div via javascript

Part of my script using the below to create the div.

days += <div class="day${i}">${i}</div>;

My question is how do I access it?

document.querySelector(“.day8”).addEventListener(“click”, () => {

Using this method works with other divs I have created but doesn’t seem to work with divs inside divs… The structure is “day” inside of “days”.

Sorry if this is not clear.

please, I can’t handle the eventlistener

I’m working on my college’s project and it’s kinda like a web-text-based game, where the player come and play. so I’m interesting in a click event on a document to change the context and I did it with the code below…. the problem is that it’s keep repeating everything and I can’t even type in the input!!

const homepage = document.querySelector('#homepage')

document.addEventListener('click',function(){
/*I console.log to check that the function is still repeating*/
console.log('check')
homepage.innerHTML = `<div> hello what's your name? </div>`
document.addEventListener('click',function() {
homepage.innerHTML = `<div> my name is <br> 
<input id="name"> </input> <br>
<button> submit </button<
`
})
})
#homepage {
  text-align: center;
}
<body>
<div id = "homepage"> click to change the content </div>

Form Input Value not updating from script

I have a text input as follows:

<td><input type="text" class="form-control assetID" autocomplete="off" placeholder="Asset ID" name="assetID[]"></td>

and a script that runs when the first input field is modified. I would like to update the value of the 2nd input when this script runs:

 $this.closest('tr').children('.form-control assetID').val(assetID);

with the value of the asset variable. I can’t get the form input to update here when this script runs and can’t see the issue here? I will have a series of similar inputs that are added dynamically so I’m not using an id for these but targeting them by the class.

What do I put in my form action when the router.post() has an :id

I am not sure how to submit data to my update form and what I have to put in the action field as the router.post has an :id. Below is my code:

router.post('/gymupdate/:id',async(req,res) => {

    
      let gymName = req.body.firstname;
      let location = req.body.city;
      let phoneNumber = req.body.mobile;
      let priceRange = req.body.price;
      let id = req.params.id;

      
     try{
      check2(gymName,location,phoneNumber,priceRange);
      if(!id) throw 'Pleaase provide an id';
      var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
      if(checkForHexRegExp.test(id)===false) throw 'Not a valid objectid';
      
    
      const updategym = await gymData.update(id,gymName,location,phoneNumber,priceRange)
      if(updategym)
        res.status(200).redirect('/gyms')
      else {
          res.status(500).render('gymbars/updategym', {title: "Error", error: 'Internal Server Error'})
      }
    }
    catch(e){
      res.status(400).render('gymbars/updategym', {title: "Error", error: e})
    }
  });

Form:

<form method="POST" action="/gyms/gymupdate/:id" id="signup-form" class="signup-form"></form>

The content in the action does not work, so how do I add id field to the action part similar to the router.post method?

Get total values from checkbox, add them, and display the result in reactjs

I have data in JSON format and it has a price. I mapped it in the table with a checkbox per row.

this is my data

{
    "CartID": "61a9d0251202a1a40825924e",
    "ShopCartList": [
        {
            "ShopID": "610a29e1d51ba524b7f949d0",
            "productCartList": [
                {
                    "ProductID": "610a40a7d51ba524b7f949f4",
                    "VariationSKU": "062104338N",
                    "Price": 478.44,
                    "Count": 1,
                    "Attribute": {
                        "Weight": "1.64",
                        "Size": "15.00"
                    },
                    "CreatedDate": "2021-12-06T07:15:59.895Z",
                    "CreatedBy": "61a9d0251202a1a40825924e",
                    "LastUpdatedDate": "2021-12-06T07:15:59.895Z",
                    "LastUpdatedBy": "61a9d0251202a1a40825924e"
                }
            ]
        }
    ]
}

I want to get the sum of the price of the checked box I selected same as Shoppee. I am using react js. How can I do this? Plz teach and help me on this thank you.

How to fix Sweetalert 2 NOT working in Google Chrome

I am trying to utilize SWEETALERT2 via php on my project but when i try to run my file in google chrome it doesn’t work. The buttons are clickable and it records the data but sweetalert doesn’t display anything just a clickable submit button.

Things that i want to achieve on this project is to use sweetalert display when i successfully record new user. When i need to update the record or to delete a file.

Submit button should not be clickable if input box has no value.

index.php

 <div class="modal-body">
<form action="add_main_users.php" id="form">
<div class="controls">
<label for="recipient-name" class="control-label" style="color: Grey">Full Name:</label>
<input type="text" class="form-control" name="fname" required data-validation-required-message="This field is required">

</div>
<div class="controls">
<label for="recipient-name" class="control-label" style="color: Grey">Username:</label>
<input type="text" class="form-control" name="uname" required data-validation-required-message="This field is required">
</div>

div class="controls">
<label for="recipient-name" class="control-label" style="color: Grey">Email:</label>
<input type="email" class="form-control" name="email" required data-validation-required-message="This field is required">
</div>

<div class="controls">
<label for="recipient-name" class="control-label" style="color: Grey">Default Password:</label>
<input type="text" class="form-control" name="dpass" required data-validation-required-message="This field is required">
</div>
                                                    
<div class="controls">
<label for="recipient-name" class="control-label" style="color: Grey">Role:</label>
<select class="form-control custom-select" name="role" required data-validation-required-message="This field is required">

<option value="Administrator">Administrator</option>
<option value="Editor">Editor</option>
</select>
</div>
<div class="controls">
<label for="recipient-name" class="control-label" style="color: Grey">Branch Assigned:</label>
<select class="form-control custom-select" name="bassign" required data-validation-required-message="This field is required">
<option value="0">1Warehouse</option>
<option value="1">2Warehouse</option>
<option value="2">3Warehouse</option>
</select>
</div>
</div>

<div class="modal-footer">
<button type="button" class="btn btn-primary" id="btnSubmit">Submit</button>
</div>
</div>
</form>
</div>
</div>```

    
add_main_users.php 
<?php
    $request = $_REQUEST; 
    $fname = $request['fname'];
    $uname = $request['uname']; 
    $email = $request['email'];
    $dpass = $request['dpass'];

    $servername = "localhost"; 
    $username = "root"; 
    $password = ""; 
    $dbname = "dims";

    $mysqli = new mysqli($servername, $username, $password, $dbname);

    if ($mysqli->connect_errno) {
      echo "Failed to connect to MySQL: " . $mysqli->connect_error;
      exit();
    }

    $sql = "INSERT INTO users (u_name, u_username, u_email, u_password)
    VALUES ('".$fname."', '".$uname."', '".$email."', '".$dpass."')";

    if ($mysqli->query($sql)) {
      echo "New user has been created.";
    } else {
      return "Error: " . $sql . "<br>" . $mysqli->error;
    }

    $mysqli->close();
?>

js



function save() 
{
    $("#btnSubmit").on("click", function() {
        var $this           = $(this); //submit button selector using ID
        var $caption        = $this.html();// We store the html content of the submit button
        var form            = "#form"; //defined the #form ID
        var formData        = $(form).serializeArray(); //serialize the form into array
        var route           = $(form).attr('action'); //get the route using attribute action

        // Ajax config
        $.ajax({
            type: "POST", //we are using POST method to submit the data to the server side
            url: route, // get the route value
            data: formData, // our serialized array data for server side
            beforeSend: function () {//We add this before send to disable the button once we submit it so that we prevent the multiple click
                $this.attr('disabled', true).html("Processing...");
            },
            success: function (response) {//once the request successfully process to the server side it will return result here
                $this.attr('disabled', false).html($caption);

                // Reload lists of employees
                all();

                // We will display the result using alert
                Swal.fire({
                  icon: 'success',
                  title: 'Success.',
                  text: response
                });

                // Reset form
                resetForm(form);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // You can put something here if there is an error from submitted request
            }
        });
    });
}

function resetForm(selector) 
{
    $(selector)[0].reset();
}

$(document).ready(function() {

    
    // Submit form using AJAX To Save Data
    save();

});