Run function passed from data attribute [duplicate] - javascript

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 7 years ago.
I want to be able to run a function that is passed by name from a data attribute on the HTML side. I've tried the following below.
HTML:
<div class="generic-select" data-help-on-shown="genericFunction" >
</div>
Javascript:
function genericFunction() {
console.log("generic function called");
}
Other Javascript (separate file):
//stepEl is correct divider from above
var genFunction = typeof (stepEl.data("helpOnShown")) === "undefined"
? null
: stepEl.data("helpOnShown");
//this prints "genericFunction" as expected
console.log("genFunction = " + genFunction);
if (genFunction) {
genFunction(); //gives error!
}
However, this gives me an error. Is there a way to call a function by a string name?

If the function is "global", it exists as a property of window:
window[functionname]()

Related

Error reading undefined ".replace()", How can I write an if statement, if condition is undefined and concates "OOS" or .replace("undefined", "OOS) [duplicate]

This question already has answers here:
Javascript: use either a variable, or if it's undefined, a default string
(7 answers)
Is there a "null coalescing" operator in JavaScript?
(19 answers)
Replace a value if null or undefined in JavaScript
(6 answers)
Closed last month.
So I have a discord command that scrapes the inventory of a website, but whenever a website doesn't have any stock for the item, it returns undefined. How would I replace "undefined" to "Out Of Stock". I've tried if(variant.inventory_quantity == undefined) { let updatedStock = variant.inventory_quantity.replace("undefined", "Out Of Stock")}, but when the command executes, it returns Error reading undefined ".replace()". I've also tried
"if(variant.inventory_quantity == undefined) {
let stock = variant.inventory_quantity.toString()
let updatedStock = stock .replace("undefined", "Out Of Stock")}, but I get the error "Error reading undefined ".toString()". Does anyone have any ideas?
axios.get(`${newLink}.json`).then((response) => {
if (response.data.product.variants) {
const { product } = response.data
let productName = product.title
atcEmbed.setColor("#2B2F51")
atcEmbed.setTitle(`Product Found! 💥`)
atcEmbed.setURL(link)
atcEmbed.setThumbnail(product.images[0].src)
product.variants.forEach((variant) => {
let cleanlink = link.split('?').toString()
let partarr = cleanlink.split("/")
cleanlink = partarr.slice(0,3).join('/')
var updatedLink = cleanlink + "/cart/" + variant.id + ":1".toString()
atcEmbed.setDescription(`**Product:** ${productName}\n**Price:** ${variant.price}\n**SKU:** ${variant.sku}`)
atcEmbed.addFields({ name: `${variant.title}`, value: `[ATC](${updatedLink})\n**Stock:** ${variant.inventory_quantity}\n${variant.id}`, inline: true })
})

Could someone poin-out why this works (JS , .bind() ) [duplicate]

This question already has answers here:
addEventListener calls the function without me even asking it to
(5 answers)
Accessing an object's property from an event listener call in JavaScript
(6 answers)
Closed 1 year ago.
can someone point out why the next code as soon as I open the live server webpage prompts me to input the number ( the one without .bind()) while the one with bind works flawlessly?
let chooseNumber;
const poll = {
question: ' What is your favorite programming language?',
options: ['0 : JavaScript', '1:Python', '2: Rust', '3:C++'],
//This generates [0,0,0,0]. More In the next section :D
answers: new Array(4).fill(0),
registerNewAnswer: function () {
chooseNumber = prompt(`${this.question} \n ${this.options}`);
if (chooseNumber >= 0 && chooseNumber < 4) {
this.answers[chooseNumber] = this.answers[chooseNumber] + 1;
}
console.log(this.answers);
console.log('Munem');
},
};
document
.querySelector('.poll')
.addEventListener('click', poll.registerNewAnswer.bind(poll)); //works
//
// document
// .querySelector('.poll')
// .addEventListener('click', poll.registerNewAnswer());
//doesn't work

What is this['string'](); in javascript and how it works; [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 2 years ago.
I searched in google but i could not find anything
test.js
class Hero(){
heroVar = 'hero1'
hero1() {
alert('I am Hero 1');
}
onClick(){
this[this.heroVar](); //this.heroVar value gets substituted with hero1
}
}
Is there any better use case,how this this[this.heroVar](); works,please explain,
does this also adds '.' in between 'this' and '[]' like this.hero1()
In Javascript class is an Object so
class Hero(){
heroVar = 'hero1'
hero1() {
alert('I am Hero 1');
}
onClick(){
this[this.heroVar](); //this.heroVar value gets substituted with hero1
// equal with this['hero1']()
// equal with hero1()
}
}

Convert MVC ViewBag property to lowercase [duplicate]

This question already has answers here:
Using Razor, how do I render a Boolean to a JavaScript variable?
(7 answers)
Closed 7 years ago.
I'm trying to use a Boolean MVC ViewBag property that is being set in a controller inside of a javascript if statement. However, there is a problem being introduced because the property value gets converted to Pascal case. For example, "true" becomes "True" and "false" becomes "False".
<script type="text/javascript">
var error = #ViewBag.Dropped;
if ( error ) {
$( '#alert-message' ).addClass('alert-success alert-dismissable');
}
</script>
How can I ensure that the property gets converted to lowercase. I've tried to use javascript function .toLowerCase() and was unsuccessful.
One way would be:
<script type="text/javascript">
var error = #(ViewBag.Dropped ? "true" : "false");
if ( error ) {
$( '#alert-message' ).addClass('alert-success alert-dismissable');
}
</script>
var error = #ViewBag.Dropped.ToString().ToLower();
I don't think the above answer will work since all strings are true in Javascript,.. you might want
<script type="text/javascript">
var error = #(ViewBag.Dropped ? true : false);
if ( error ) {
$( '#alert-message' ).addClass('alert-success alert-dismissable');
}
</script>
note if you quote true and false they become strings and true is NOT the same as "true".
I use this method all the time because the longer version (value.ToString().ToLowerInvariant()) is too tedious to type all the time:
Add a class to your project or library:
public static class ExtensionMethods
{
public static string ToJS(this bool value)
{
return value.ToString().ToLowerInvariant();
}
}
then in your js:
<script type="text/javascript">
var error = #ViewBag.Dropped.ToJS();
if ( error ) {
$( '#alert-message' ).addClass('alert-success alert-dismissable');
}
</script>

How to add the value of a variable to my HTML? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have 2 separate instances in which I show Data from JavaScript in a heading on my page:
Html:
<h2 id='Fetch_Header' style="color:white; font-family: arial;">
The last time you fetched your games was:<span class="last_fetch" style="font-weight: bold;"></span>
</h2>
jQuery:
$.get('php/FetchGames/LastFetch.php', function (data) {
if (data == "Never") {
var lastdate = data;
$('.last_fetch').html(" " + lastdate);
}
more jQuery:
$.get('php/FetchGames/GetMatchCount.php', function (data) {
MatchCountJson = data;
MatchCountJson_Parsed = JSON.parse(MatchCountJson);
MatchCount = MatchCountJson_Parsed.Int;
//the above JSON is {"Int":72}
});
$('#Fetch_Header').html('Time to apply your MMR, follow the instructions below. Matches left to apply: ' + MatchCount);
However only the former works (The lastdate one).
First Output:
date (as expected)
Second Output:
"Time to apply your MMR, follow the instructions below. Matches left
to apply: undefined"
Both of the variables are not null/undefined, since if I use Console.log, then the lastdate is a date, and the Matchcount is an integer (for example 32).
Matchcount is outside of the scope of your code when you try and use it.
.get() is an asynchronous call, meaning it is not guaranteed to be complete when the next instruction is executed. If you want to use anything based on data, it needs to happen within the scope of the callback function in the get() call.
$.get('php/FetchGames/GetMatchCount.php', function(data){
MatchCountJson = data;
MatchCountJson_Parsed = JSON.parse(MatchCountJson);
MatchCount = MatchCountJson_Parsed.Int;
// Call must be inside of "get()" callback
$('#Fetch_Header').html('Time to apply your MMR, follow the instructions below. Matches left to apply: '+MatchCount);
});
You can only use your MatchCount variable in the result of the get method.
Try this
$.get('php/FetchGames/GetMatchCount.php', function(data){
MatchCountJson = data;
MatchCountJson_Parsed = JSON.parse(MatchCountJson);
MatchCount = MatchCountJson_Parsed.Int;
//the above JSON is {"Int":72}
$('#Fetch_Header').html('Time to apply your MMR, follow the instructions below. Matches left to apply: '+MatchCount);
});
The issue is the scope of the data passed back from the server so your second html insert cannot access MatchCount. Change your code to this:
$.get('php/FetchGames/GetMatchCount.php', function(data){
MatchCountJson = data;
MatchCountJson_Parsed = JSON.parse(MatchCountJson);
MatchCount = MatchCountJson_Parsed.Int;
//the above JSON is {"Int":72}
$('#Fetch_Header').html('Time to apply your MMR, follow the instructions below. Matches left to apply: '+MatchCount);
});

Categories

Resources