Dynamic string wont change when changing the values that make it - javascript

http://jsfiddle.net/zzTsc/
I have a JSON that holds some values which get concatenated into a string but when I change the value of the JSON the string doesn't take the name values. How can I make the string take the new values without re-declaring the same string?
See I could easily put string = name.first + "<br />"+name.last; right below where I change the JSON value but then when I wanna edit the format of that string I'll have to change it twice.

That's not how variables work. You have to set the value of string again for it to update.
Here's an improved version so you don't have to change it twice if you want to edit something:
function generateString(name) {
return name.first + "<br />"+name.last;
}
var string = generateString(name);
​Demo

That's not going to work as you describe it, but you could declare a function which returns the appropriate string.
So instead of
string = name.first + "<br />" + name.last;
You'd have:
var stringfunction = function() {return name.first + "<br />" + name.last;}
and when you wanted to use it you'd call it:
alert(string); //old
alert(stringfunction()); //new
EDIT: I just realized you're talking about changing the format (presumably at runtime). There are a number of ways to use string formats in javascript, meaning that you could have a "format" variable used inside the stringfunction, which you could change at runtime to modify how the resulting string is formatted. It's been too long since I used one of those tools though, so I'll leave it to someone else to explain how to do string formatting in javascript.

This is because your string is a basic type and therefore holds the actual data instead of a pointer. When you change the data you think should change the string, it only changes the data. This can be seen by just re-issuing the code used to construct the string
$('#test').empty().append(name.first + "<br />"+name.last);
http://jsfiddle.net/zzTsc/4/

Related

Multiple attribute on href using onclick

I Tried this code to get multiple value in href but it does not work. any problem on this one ?
Print
You are missing a + sign between a string and a value.
The error is between this two
document.getElementById('CUS_CODE_MX').value '&AGE='
Correct format
document.getElementById('CUS_CODE_MX').value + '&AGE='
Every time you join a value and a string, you need a + sign
Even if you are joining two strings
'Hello'+ 'World'
Pliss avoid long js as an inline atribute. I will recommend you call a function as the onclick attribute.
Hope this helps :)
Print
It's better to use external script for that rather than inline format. And just add missing + to your code. Also, using variables would clean up the code.
function func() {
var CUS_CODE_MX = document.getElementById('CUS_CODE_MX').value;
var AGEID = document.getElementById('AGEID').value;
this.href = 'printsales.php?CUSTOMERID='+CUS_CODE_MX+'&AGE='+AGEID;
}
Print

Store data having a double quote in a javascript var

I have a var in script which has data like . But when i add this to another variable its not working.
var x = '32"';
onclick="javascript:selectSize(' + "'" + x + "'" + ');"
I want
onclick="javascript:selectSize('32"');"
But it becomes
onclick="javascript:selectSize('32"');""=""
i don't know whats happening
onclick="javascript:selectSize('32"');"
^ ^
The HTML parser will parse the attribute value before passing the value of it to the JS engine for execution.
You are using a " to delimit the attribute value.
The second " ends the attribute value.
If you want to use " as data in an attribute value delimited with " then you must express it as an entity (e.g. ").
var html_x = x.replace(/"/g, """);
Escaping becomes very painful when you start generating nested languages.
You have JavaScript embedded in HTML embedded in JavaScript.
Avoid mashing strings together to construct your DOM. Use DOM methods directly instead.
var x = '32"';
var button = document.createElement("button");
button.addEventListener("click", function (event) {
selectSize(x);
});
from comment, Make use of encode/decode URI Component as follows
var a=encodeURIComponent('abc"');
console.log(a);
console.log(decodeURIComponent(a));

Unable to get value of JavaScript Object [duplicate]

I'm looking for an easy way to assign to a variable depending on the value of another variable.
device.slot2_clipList[clipNumber] = singleClipDetails;
what I'm trying to do is: replace the "2" with another variable, so that i can run the same operation while just changing the
var slotNumber, and write to the corresponding variable.
i tried
device.slot + device.slotNumber + _clipList[clipNumber]
but (obviously?), this doesn't work.
How can this be done? (Maybe I named the Question incorrectly, but that was the closest I could think of.)
Thanks
This is what bracket notation is for
var i = 2;
device['slot' + i + '_clipList'][clipNumber] = singleClipDetails;
device['slotNumber' + _clipList[clipNumber] ]
Explanation:
foo.bar in javascript is identical (even in performance) to foo['bar']. So any object property name can be built up from strings.

Creating a JavaScript function to change a previously declared variable

I am having trouble changing a variable on a page with lots of PHP and JavaScript.
This part is working fine for me:
<script language="javascript" type="text/javascript">
function changebg(my)
{
document.getElementById("imglayer").style.backgroundImage ='url('+ my.src +')';
document.getElementById("cropframe").style.backgroundImage ='url('+ my.src +')';
}
var test2 = new String("url('+ my.src +')");
</script>
<img src="../../uploads/595MCoDFyArFFe.jpg" width="50" height="50" onclick="changebg(this)" >
<img src="../../uploads/P6l6J8aqzli6gh.jpg" width="50" height="50" onclick="changebg(this)" >
<img src="../../uploads/stXWS8fL4L3nvs.jpg" width="50" height="50" onclick="changebg(this)" >
with the div IDs being called for later.
My issue is I have another variable that I need to change dynamically:
<script type="text/javascript">
var test1 = new String( "<?php $src_name = '" );
var test2 = new String( "956ENbXjzTlkBo.jpg" );
var test3 = new String( "'; // modify this, original file?>");" );
document.write( String( test1, test2, test3 );
</script>
I need var test2 to change with the other two which are being grabbed by the div ID.
How do I change that string value? Is this even possible?
Any help would be greatly appreciated!
First of all, this is not Java (and even in Java you do not really need it). You should not use new String(…); simply use string literals:
var test1 = "…";
etc.
Second, strings are immutable; you cannot change a string value/object; you can only create and assign a new string. However, you can also create a user-defined Object instance that has a method that returns a value according to other values (like variable values):
var test2 = {
toString: function () {
return "foo" + test1 + "bar";
}
};
The document.write() DOM method implicitly converts its argument to string, which is done by calling either the hull object's toString() or valueOf() method, whichever is available first (see the ECMAScript Language Specification, 5.1 Edition, section 9.8). So
document.write(test2);
is equivalent to
document.write(String(test2));
(section 15.5.1) or
document.write(test2.toString());
It will write the return value of the toString() method of the object referred to by the value of test2. (For dynamic change of the output, you need to use other DOM features, such as the standards-compliant textContent, nodeValue, or the proprietary innerHTML property.)
BTW, the String constructor only considers one argument (see above), so new String(x, y, z) is equivalent to new String(x). Perhaps you were looking for concatenation: new String(x + y + z). But if at least one operand is of type String, x + y + z suffices; if not, String(x) + y + z or "" + x + y + z works.
Just use the right quotes:
var test2 = new String("url(" + my.src + ")");
Or simply:
var test2 = "url(" + my.src + ")";
However, you can't change a php variable by writing php code from Javascript. When the Javascript runs, the php script has aready ended.
First off, you're going a very weird way about building a string. I assume the point of this is to, at the end of all of this, end up with a string that looks like this:
<?php $src_name = 'X'; // modify this, original file ?>
(This outputs PHP, which won't be interpreted by your web server, but I'll assume you know that and you're outputting it for other reasons.)
Where x is some piece of data that's available in some other DOM element (one of your img elements, perhaps, since the filenames are similar). If you then want to, after some future arbitrary event occurs, update this x value that has been printed to the page. You'll need to give yourself some tangible element to update - for example, a span element.
Try document.write()ing this:
document.write("<?php $src_name = '<span id=\"my-element\">X</span>'; // modify this, original file ?>");
Note I've changed your < and > to their encoded equivalents.
Then, you can update the contents of your span using JavaScript at a later date (see below). This isn't changing the variable you have declared, but rather it is changing the contents of the page. Since you are just printing your string at the end of it all (or, trying to, since String() won't concatenate the given strings like you seem to think it will), it seems to me like this is what you're trying to accomplish.
document.getElementById("my-element").innerText = "NEW VALUE";
Again, this is not updating the variable, per se, just updating the text that you are printing to the page. This seems to be your end goal anyhow, correct me if I'm wrong.

call a javascript function based on a regex match

In the following string, i would like to replace [choice:a3d] with an appropriate drop down menu. I am not sure of how the options need to be formatted just after the colon and before the closing square brace.
string = "operation [number] [choice:a3d] [number]";
I am not really sure where the .replace function comes from but the code I am working with has jquery imported.
string.replace(/(?:\[choice\:)(\w+)(?:\])/g, choice_func);
where:
function choice_func(choice_lists, listname, default_opt)
{
console.log("choice_lists: "+choice_lists); // [choice:a3d]
console.log("listname: "+listname); // a3d
console.log("default_option: "+default_opt); // 67
var list = choice_lists[listname];
return '<span class="string ' + listname + ' autosocket"><select>' +
list.map(function(item)
{
if (item === default_opt){
return '<option selected>' + item + '</option>';
}else{
return '<option>' + item + '</option>';
}
}).join('') +'</select></span>';
}
needless to say the code fails with error "Uncaught TypeError: Cannot call method 'map' of undefined"
also where do parameters to the function come from?
Don't assume that any of this code is correct....
This looks to me like it would be simpler for you to just use whatever code you need to use to compute the replacement string and then just do a replace using the string instead of the regex function. Regex functions are best used when you need to examine the context of the match in order to decide what the replacement is, not when you are just doing a replacement to something that can be computed beforehand. It could be made to work that way - there's just no need for that level of complexity.
When using regex callbacks, the callback gets multiple parameters - the first of which is the match string and there are a number of other parameters which are documented here. Then, you must return a string from that function which is what you want to replace it with. You function is pretending that it has three parameters which it does not and thus it won't work.
I suggest that you compute the replacement string and then just do a normal text replacement on it with no regex callback function.
If you can be clearer about what the initial string is and what you want to replace in it, we could give you some sample code that would do it. As you've shown in your question, your string declaration is not even close to legal javascript and it's unclear to me exactly what you want to replace in that string.
The pseudo code would look like this:
var menuStr = "xxxxxxx";
var replaceStr = choice_func(lists, name, options);
menuStr = menuStr.replace(/regular expression/, replaceStr);

Categories

Resources