2

I have a response from an AJAX request and depending upon the situation that calls it, I want to either replace the data on the screen, or append new data to the screen.

Two possibilities are as followed:

$('#data').append(response);
$('#data').html(response);

I tried to do something like:

var action = "append"
$('#data').(action)(response)

That didn't work, how can I do this?

freedomn-m
  • 27,664
  • 8
  • 35
  • 57
  • 1
    Or (perhaps better): https://stackoverflow.com/questions/17025891/how-to-call-a-function-by-a-variable-name and https://stackoverflow.com/questions/912596/how-to-turn-a-string-into-a-javascript-function-call leading to: https://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string – freedomn-m Apr 15 '20 at 14:46

1 Answers1

3

The function is a property of the object on which you're calling it, which can be indexed by its name:

var action = "append";
$('#data')[action](response);
David
  • 208,112
  • 36
  • 198
  • 279
  • A [little demonstration](https://jsfiddle.net/jxfd974s/). – showdev Apr 15 '20 at 14:46
  • 2
    @CenterTruth: It's also worth noting that this isn't specific to jQuery, this is just JavaScript syntax. An object's properties (which includes its functions) can simply be referenced by their name as an index like this. JavaScript is the only language I've used which does this, though there may be others, but it's super useful. – David Apr 15 '20 at 14:47
  • 1
    Looks like python has something similar: https://stackoverflow.com/questions/39960/javascript-equivalent-of-pythons-locals – freedomn-m Apr 15 '20 at 14:48
  • yes indeed it is, thanks for the help. are closed questions still available to public view? – Center Truth Apr 15 '20 at 14:49