Multiy String Variable Names Not Working In Javascript - javascript

Recently I posted about Dynamic Names in Javascript. I went ahead and tried to make a multi string variable name (combining a string and a variable to make a new variable name), and it does not seem to work. I am very confused because I am doing what many posts on SO say to do (so I think anyhow).
Anyhow here is the dynamic variable I am using:
var dynamic["replyupvote"+replyid] = false;
and then when I am calling it I use:
dynamic["replyupvote"+replyid]
So my question is where am I going wrong? If you would like to see my full code:
function replyupvote(replyid, upvotes, downvotes, votesclass, votesnumber) {
var dynamic["replyupvote"+replyid] = false;
return function() {
if (dynamic["replyupvote"+replyid]) {
dynamic["replyupvote"+replyid] = true;
}
else {
$.ajax({
url: "http://localhost/postin'/categories/votes.php",
type: "POST",
data: { 'itemid': replyid,
'userid': <?php echo $_SESSION["logged_in"]; ?>,
'action': "upvotes",
'type': "reply" },
success: function() {
$("." + votesclass).css("color", "orange");
$("." + votesnumber).text(parseInt(upvotes - downvotes) + 1);
}
});
dynamic["replyupvote"+replyid] = true;
}
}
}
This code worked before I through in the Multi String Variable Names. So what am I doing wrong? Thank You! :)
EDIT
I thought I should throw this in. Javascript throws the error that the function is not defined because of the incorrect syntax.

Regardless if what you are doing here makes sense or not, to dynamically create properties on an object, you will need to make sure JS knows it's an object, not an array. So before you try to create a dynamic object property, explicitly declare dynamic as an object:
var dynamic = {};
dynamic["replyupvote"+replyid] = false;
That should get rid of the syntax error at least.

You would have to set dynamic as an object first
var dynamic = {};
dynamic["replyupvote"+replyid] = false;
variableName[keyName] = value; is the syntax of an object.
You have to tell js that your variable is an object before you can use this notation.

Related

Storing Jquery reference

Is it possible to store the reference to an element in an array or object without having a unique ID on the element?
I am having trouble with storing a subtable in another table so I can reference it later. I get the table by class with this code:
$(this).parent('tr').parent().find('.tableSomeTable');
Is the only solution to have unique id's on each element and use the .selector method?
More of my code. Abit simplified.
var rows = [];
var historyLoad;
$(document).on("click", '.details-control', function (e) {
var t = $(this);
var tr = t.closest('tr');
var row = t.parent().parent().parent().DataTable().row(tr);
var id = t.closest('tr').attr('id');
var object = {
id: id,
btnHistory: t.parent('tr').next().find('#btnHistory'),
tblHistory: t.parent('tr').parent().find('.tableHistory'),
historyLoad: historyLoad
};
if ($.inArray(id, rows) > -1) {
loadData = false;
}
else {
loadData = true;
loadHistory(object);
rows.push(object);
}
};
Here is where I am having trouble retrieving the correct elements. And I also want to save the ajaxHistory element to my object (which is working fine).
This code is not working, but if I change it to $(result.btnHistory.btnHistory.selector) I get the object. But this doesn't seem to work very good with multiple rows.
function loadHistory(result) {
result.ajaxHistory = $.ajax({
...
beforeSend: function () {
$(result.btnHistory).html(<loading txt>);
$(result.tblHistory).find('tbody').html(<loading txt>);
},
....
success: function (data) {
if (data.TotalRecordCount > 0) {
$(result.tblHistory).find('tbody').html('');
$.each(data.Records, function (e, o) {
$(result.tblHistory).find('tbody').append(<data>)
});
}
else {
$(result.tblHistory).find('tbody').html(<txt no records>);
}
$(result.btnHistory).html(<txt loading done>));
},
First off, if you are trying to find the parent table, try
var $myObj = $(this).closest('table.tableSomeTable');
instead of navigating parents.
As far as storing the jQuery reference, define a variable and then store it. The above will store the object in $myObj but that is locally scoped. If you need a global variable then define it globally and just assign it here. If you want to define it as a property within an object then define it that way. It really comes down to a scope question at this point.
EDIT: Just saw your added content.
First off, don't name it 'object'. This may run into key word issues. Use var myObj or similar instead. Next, object.btnHistory is a reference to a jQuery object. So, when you pass it to loadHistory, you do not need to apply the $(...) again. Just use the reference directly: result.btnHistory.html(...). A good habit to get into is prepending you jQuery variables with $ so you remember it is already a jQuery variable.
The .find() method returns a jQuery object. So the answer is, yes, you can store this return object in a variable:
var $yourObject = $(this).parent('tr').parent().find('.tableSomeTable');

efficiently creating variables when a checkbox is checked and using these variables later in the code

below is the information I need help with.
$(document).ready(function(){
$('.checkboxes :checkbox').click(function(){
if($(this).is(':checked')){
console.log(this.id + this.checked)
i want to set a variable with the samename of the id of the checked box
so if showItems was checked i would have a variable
var showItems = true;
I want this so I could see if showItems is checked which would alow me to perform the proper functions
i think i could do something like this
if($this.id = "withones"){
var withones = true;//on
}
if($this.id = "withoutOnes"){
var withoutOnes = true;//on
}
etc.
i feel like the above is a rookie way to code. lets say i have alot of checkboxes and it also looks like im repeating myself. I tried putting the ids in an array and loop through them but I got the html element in the console when i clicked on the box. I would like for someone to tell me if there is a more efficient way to set up these variables. and if so show me please.
Also I'm new to programming so thanks for your help so far. but I was also thinking about another problem. if I set up these variables here and I want to set up another function somewhere else to perform mathematical operations perse. i want that function to be able to evaluate the value of the withones and withoutOnes variables so I would like to do something like this in the function
function add(){
if(withones){ //true|| false
return 2 + 2;
}
if (withoutOnes) {
return 'blah'
};
}
I have had problems in the past trying to test the values that are set outside the function. I think i tried setting it in the arguments. but it just didn't read. If you could also show me an example of using the variables some where else in the code like discussed above that will be helpful . I forgot to mention that the value of the variable will change when the user clicks on the box. either to true or false. I think my problem in the past is that when the box is checked and then uncheck I had a problem changing the variable especially when it is being used in a separate function
}
});
});
You can have an object with your vars and add vars to that object dinamically:
var oVars = {}
// adding a var
oVars[nameVar] = valueVar
// accessing the var
oVars[nameVar]
You can capture the id with the attr() or you can just change the value of the checkbox with val() method in jQuery like this: FIDDLE
$(document).ready(function () {
$('.checkboxes').change(function (event) {
if ($(this).is(':checked')) {
var captureId = $(this).attr('id');
$(this).val(true);
alert($(this).val());
}
else {$(this).val(false);
alert($(this).val());}
});
});
Note that you can evaluate later all the checkboxes with one button and collect the value false or true from them. Why would you go through all of the complications with changing values of variables.
The other two answers are correct, though it sounds like you're wanting to know generally how to manage a big list of checkboxes with differing methods depending on type. It could look like this:
function multiply(this_object){
if((this_object.is(':checked')) && (this_object.attr("with") == 1))
return "with withone and checked";
else
return "is not both";
}
$(document).ready(function(){
$('.checkboxes').click(function(){
var this_object = $(this);
alert(multiply(this_object));
});
});
There should be no need to store all of the values in a variable unless you are passing all of them to another page - eg., via AJAX. Just reference them straight from the source field. If you need other info stored alongside, make a new attribute on the field - like the "with" one that I made for this example. See this Fiddle: http://jsfiddle.net/6ug6gL97/
your question is quite broad; so I’ll try to do my best to give you some kind of answer. First of all I’d use variables of global scope when declaring variables: withones and withoutOnes. Secondly, you wanted to avoid repetition in your code. Well, for that purpose I’d use JavaScript Arrays. In an array, you can add your variables as objects. In an object you can have your ids and other data “packed” neatly in the array, which in turn helps your code to become efficient.
Below is an array with objects:
objectArray = [{
id: "withones",
checked: false,
method: function () {
return 2 + 2;
}
}, {
id: "withoutOnes",
checked: false,
method: function () {
return 'blah';
}
}];
The above array can be used in your $('.checkboxes :checkbox').click(function() handler and add() function to avoid repetition. The updated code is below where jQuery's each() method is used for looping Array elements.
The last a bit of your question was related to add() function. Well, this was the tricky bit of your question, and I tried to use a callback function hopefully in the right way to execute your functions from the array. In the add method I tried to follow this answer: https://stackoverflow.com/a/13343452/2048391
About the last bit I’m not 100% sure did I use a callback function in the right way; so I hope someone more familiar with these tricky JavaScript functions can correct me, if something needs to be changed –thanks.
objectArray = [{
id: "withones",
checked: false,
method: function () {
return 2 + 2;
}
}, {
id: "withoutOnes",
checked: false,
method: function () {
return 'blah';
}
}];
$(document).ready(function () {
$('.checkboxes :checkbox').click(function () {
var id = this.id;
var checkedValue = this.checked;
$.each(objectArray, function (index, object) {
if (object.id === id) {
object.checked = checkedValue;
}
});
add();
});
function add() {
// clear results
$("#addResults").text("");
$.each(objectArray, function (index, object) {
if (object.checked === true) {
var returnValue = createCallback(object.method)
$("#addResults").append(returnValue + "<br>");
console.log(returnValue);
}
});
}
function createCallback(method) {
return method();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="checkboxes">
<input type="checkbox" id="withones"></input>
<label>With Ones</label>
<br>
<input type="checkbox" id="withoutOnes"></input>
<label>Without Ones</label>
</div>
<div id="addResults">
</div>

how to get a property name which represent a function in JS

This is some JS code
var methodArr = ['firstFunc','secondFunc','thirdFunc'];
for(var i in methodArr)
{
window[methodName] = function()
{
console.log(methodName);
}
}
My problem is that how to get the name of a function in JS.
In JS, use this.callee.name.toString() can get the function name. But in this situation, it is a null value. How can i get the 'funName' string?
Sorry, I didn't make it clear.
I want to create functions in a for loop, all these functions has almost the same implementation which need its name. But others can call these functions use different name.I want to know what methodName function is called.
it seems a scope problem.
Try this:
var methodArr = ['firstFunc','secondFunc','thirdFunc'];
for(var i in methodArr) {
var methodName = methodArr[i]; // <---- this line missed in your code?
window[methodName] = (function(methodName) {
return function() {
console.log(methodName);
}
})(methodName);
}
window['secondFunc'](); // output: secondFunc

Store jquery function on variable

I have this code in .js file:
$.getJSON('http://api.wipmania.com/jsonp?callback=?', function (data) {
if (data.address.country='spain') {
var a="http://www.link1.com";
} else {
var a="http://www.link2.com";
}
return a;
});
var fan_page_url = data();
How can I store var a in var fan_page_url ?
Thank you very much.
Try getting rid of a and assigning the links directly.
var fan_page_url;
$.getJSON('http://api.wipmania.com/jsonp?callback=?', function(data) {
if (data.address.country = 'spain') {
fan_page_url = "http://www.link1.com";
} else {
fan_page_url = "http://www.link2.com";
}
});
You have two options: assigning the external variable directly, as depot suggested, or treating the $.getJSON return value as a Deferred:
$.when($.getJSON(...)).done(function(returnValue) {
fan_page_url = returnValue;
});
The latter is useful in case you don't want to hardcode the variable you'll store the results (though in general it's not a problem, and the former option is easier/cleaner).
It's an old question on which I just stumbled (looking for something slightly different) but as answers did not seem to hit the nail on the head, I thought I'd add 2 cents: if you (op) had success with a variable that was hardcoded and set manually in config.js, that you were able to grab from start.js, why not simply:
keep the variable declared like you did in the global scope
assign it a default or null or empty value:
var fan_page_url = null; // or
var fan_page_url = ''; // or
var fan_page_url = 'http://url_default'; // etc...
then update the global variable inside the json function:
$.getJSON('http://api.wipmania.com/jsonp?callback=?', function(data) {
if (data.address.country='spain') {
fan_page_url = "http://url1";
} else {
fan_page_url = "http://url2";
}
});
in your start.js page, you can always perform a check to see if the variable is set or not, or still carries it's default value or not and act accordingly...
It is likely that if it used to work with your normally, manually declared variable, it would work the same here as you would have changed nothing structurally, only would be updating the variable after the json response.
Answer posted for the posterity, it may help someone in the future.

Error ' missing : after property id' when using Jquery ajax function

In the following code, I'm trying to send a key-value pair and I always get the error:
" missing: after property id "
$(".general").change(function () {
fields = { $(this).attr('id') : "1" };
$.ajax({
type: "POST",
url: "ajax/update_general.php",
data: { fields: fields },
dataType: "json",
});
})
I've figured that what causes the problem is:
$(this).attr('id')
But I have no clue why. I've tried to first assign $(this).attr('id') to a variable, and put the variable in the ajax call, but that didn't help.
How can I fix that?
Thank you!
It's a syntax error. You can't use the return value of a function call as a property name.
You can, however, use that return value in bracket notation after initializing the object:
fields = {};
fields[$(this).attr('id')] = '1';
When declaring object with {} syntax, ONLY strings (like {'foo':1}) or bare string is allowed ({foo:1})
You should write something like this:
var fields = {};
fields[$(this).attr('id')] = 1;
Change this line:
fields = { $(this).attr('id') : "1" };
to this:
fields = $(this).attr('id') || "1";
That's if you intended to have something like a default value.
If you want an object, use this:
fields[$(this).attr('id')] = "1";

Categories

Resources