Angular change PUT request to PATCH

I am calling an API for updating Project name, description and using ID. I have a PUT request that updates all the data. But I want to update only Project name and description. I am not able to perform the PATCH call provider. Can someone tell me how to call the PATCH request
thanks.

This is my PUT request. And I want PATCH request

put(apiUrl, data) {
const apiURL = environment.endPointUrl + apiUrl;
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    AuthenticationKey: `${CryptoJS.AES.decrypt(
      localStorage.getItem('UAuthToken') == null
        ? ''
        : localStorage.getItem('UAuthToken'),
      environment.EncryptionKey
    ).toString(CryptoJS.enc.Utf8)}`,
  }),
};
return this.http.put(apiURL, data, httpOptions);

}

This is my Service.ts

UpdateProject(data){
const apiURL = 'http://192.168.1.22:8080/TestExpress/projects/updateProject/projectDescription/projectId/projectName';
return this.callProvider.put(apiURL, data);

}

Custom Validator function with Button on Client Click – Javascript

I have a textbox to which I have assigned a CustomValidator which has a ClientValidationFunction=”txtcheck”

ASPX:

<asp:TextBox ID="txt1"  MaxLength="10" CssClass="class1" Width="90%" runat="server"></asp:TextBox>
<asp:CustomValidator runat="server" ID="valtxt1" ControlToValidate="txt1" ValidateEmptyText="true" ValidationGroup="Save" Display="Dynamic"
                        ClientValidationFunction="txtcheck" Font-Italic="True"></asp:CustomValidator>
<asp:Button ID="btnSave" Text="Save" CausesValidation="True" runat="server" ValidationGroup="Save" OnClientClick="show()" UseSubmitBehavior="false" />

Javascript :

The alert messge is mandatory as it is required.

function txtcheck(source, args) {
Alert('incorrect value');
args.IsValid = false;
}

function show(){
var validated = Page_ClientValidate('valSave');
    if (validated) {
-- show some data.
      }
}

On click of Save Button I do a Page_ClientValidate to check other controls.

The issue is, on click of Save; txtcheck() is getting called twice.
Once via the CustomValidator & other when I do the Page_ClientValidate. Due to this the Alert message is also shown twice.

Pls guide as to how to call the txtcheck() only once & show alert once.

Any help is greatly appreciated.

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;
  }

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>

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

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?