replace the text of a variable - javascript

I am trying to replace the text from one variable to another but this tells me: newLinkRef is not defined
<script>
$('.sous_img_montureCard').click(function(){
var idMiniatureRef = $(this).attr('id');
var linkRef = $(this).parents('.montureCard').children('.CardReferenceEnvies').children('.divCardRef').children('.sousDivCardRef').children('p');
newLinkRef.replace(linkRef, idMiniatureRef);
$(this).parents('.montureCard').children('.CardReferenceEnvies').children('.divCardRef').children('.sousDivCardRef').children('p').html(newLinkRef);
});
</script>
I had succeeded with
var newLinkRef = linkRef + idMiniatureRef;
but that adds [OBJECT OBJECT]3CLA02A
and I just want 3CLA02A

It's because you haven't defined newLinkRef before. Define it, then replace.

As the error says, newLinkRef is not defined. define it with var, set a value to it, and then you can call .replace() or any other method on it.

I just found my concern, it was simply:
var newLinkRef = idMiniatureRef;
I was absolutely looking to put a replace () x)

Related

What's wrong with this var statement declaring a variable with a dot in the name?

I'm new to JavaScript and I get an error saying that my code is missing semicolons on line 2. What semicolons does it need? I already put semicolons.
var success = function(){
var wx.varx = $scope.vr;
$state.go("/there");
};
The problem with that line is that it's simply invalid. The error message is just the parser doing its best to figure out what's going on.
var declares a variable. Literal variable names (IdentifierName in the spec) cannot contain a ..
If you have an in-scope wx identifier referencing an object and want to set a property on it, remove var:
wx.varx = $scope.vr;
If you want to create a new variable, remove the . from the name.
var wxvarx = $scope.vr;
If you want to create a wx variable and an object containing varx as a property:
var wx = {
varx: $scope.vr
};
Use like this
var wx={};
wx.varx = $scope.vr;
You cannot use variable directly as an object
You cannot declare an object property directly using
var wx.varx
As the object does not exist at this point. Instead you need to declare the object (wx) and set varx.
var vx = {
varx: $scope.vr
};

JS: Including a variable name into another variable name possible?

So for example I am trying to do a for loop in JS
for (var i=0;i<result.length;i++){
var btn[i] = document.createElement("BUTTON");
var t[i] = document.createTextNode("CLICK ME");
btn.appendChild(t[i]);
}
the i being the delimiter, is it possible to append it to another variable name like above when I try to create an element? Just to make the variable name unique. Right now I am trying with the square brackets and it's giving me an error saying unexpected []. Any help is appreciated thanks!
In browsers (I've never done any node.js stuff) the global scope lives in the window object.
bla = 'test';
window['bla'] == 'test';
This means that you can create a variable say test1 like this:
window[bla + 1] = 'foo';

Changing variable name with javascript and jQuery

How to shift between variable names in jQuery and change them?
//predefined variables
var s1='';
var d2='';
//trying to change variables by .attr() parameter but no luck
$('body').on('click','span', function() {
var $(this).parent().attr('data-scan')=$(this).attr('id');
});
HTML
<div data-scan="s1"><span id="banana">Banana</span><span id="apple">Apple</span></div>
<div data-scan="d2"><span id="orange">Orange</span><span id="apple">Apple</span></div>
How can I change specific variables? I do't care about changing attr papameter, all I need is changing predefined global var parameters!
You are using wrong syntax of attr()
Syntax: attr( attributeName , value)
Change
var $(this).parent().attr('data-scan')=$(this).attr('id');
To
$(this).closest('div').attr('data-scan',$(this).attr('id'));
You code would be
Live Demo
$('body').on('click','span', function() {
debugger
$(this).closest('div').attr('data-scan',$(this).attr('id'));
s1=$(this).closest('div').attr('data-scan');
alert(s1);
});​
Firstly, your html for the data-scan attributes is wrong, you have no closing quotes.
Secondly, you can the data() jquery function to access data attributes.
Thirdly, you cannot set values by using the = operator.
You want something like this:
$(this).parent().data('scan', $(this).attr('id'));
or, without the data() function:
$(this).parent().attr('data-scan', $(this).attr('id'));
Here is a working example
To get the value you can do one of the following:
var dataScan = $(this).parent().data('scan');
or
var dataScan = $(this).parent().attr('data-scan');
Your exact requirements for setting a variable based on the data-scan value
Based on your comments and code, I think it has not been clear what you were trying to do. I think I have worked it out though and you want to use the data-scan value to determine which global variable should be set...
//predefined variables
var s1='';
var d2='';
$('body').on('click','span', function() {
var variableType = $(this).parent().data('scan');
var valueToSet = $(this).attr('id');
if(variableType == "s1"){
s1 = valueToSet;
}
else if(variableType == "d2"){
d2 = valueToSet;
}
});
Here is an example of what I think you are trying to do.
However, if you have lots of variables then it is not ideal to use so many if/else statements. So you could use the javascript eval() function.
var variableType = $(this).parent().data('scan');
var valueToSet = $(this).attr('id');
eval("" + variableType + " = '" + valueToSet + "';");
See here for an example
But be careful the your eval code is subjected to user injected values (not that javascript is safe from users anyway)
You're pretty close!
// set
$('#item').attr('data-scan', 'set new value');
// get
var dataScan = $('#item').attr('data-scan');
console.log(dataScan); //=> set new value
Probably best if you use .prop() rather than .attr()
$(this).parent().prop('data-scan', $(this).attr('id') );
As the jQuery api documentation states
As of jQuery 1.6, the .attr() method returns undefined for attributes
that have not been set. In addition, .attr() should not be used on
plain objects, arrays, the window, or the document. To retrieve and
change DOM properties, use the .prop() method.

Object arrays in JavaScript

If I do this,
var element = {};
alert(element);
element[name] = "stephen";
alert(element.name);
Why doesn't element.name work?
When using bracket notation, (unless it's a variable) it needs to be in qoutes, like this:
var element = {};
alert(element);
element["name"] = "stephen";
alert(element.name);
You cant test it out here. To explain what I mean by "unless it's a variable", this would also work:
var myVariable = "name";
element[myVariable] = "stephen";
Because name should be in quotes.
This works:
var element = {};
alert(element);
element['name'] = "stephen";
alert(element.name);
Try it.
This is the reason why you may want to get an object's property dynamically. For example:
You have a variable, but you can't be sure of its value. The server send you the variable value so you should write like this.
obj[name].age // Here the name is a variable, and it can be changed in every page refresh, for example.
But if you want to set obj['name'] = 'Lorenzo' you have to use quotes.
Think like obj[name] is used for set, obj['name'] is used for get.

Executing a function by name, passing an object as a parameter

Here's the problem - I know function by name (and that function has already been loaded form an external script), but I don't have an actual function object avail for me to call. Normally I would call eval(function_name + "(arg1, arg2)"), but in my case I need to pass an object to it, not a string.
Simple example:
var div = document.getElementById('myDiv')
var func = "function_name" -- this function expects a DOM element passed, not id
How do I execute this function?
Thanks!
Andrey
Never use eval, it´s evil (see only one letter difference)
You can simply do:
var div = document.getElementById('myDiv');
var result = window[function_name](div);
This is possible because functions are first class objects in javascript, so you can acces them as you could with anyother variable. Note that this will also work for functions that want strings or anything as paramter:
var result = window[another_function_name]("string1", [1, "an array"]);
You should be able to get the function object from the top-level window. E.g.
var name = "function_name";
var func = window[name];
func( blah );

Categories