pass toString(number) in innerHTML - javascript

This is my first post, I am "new" to javascript but experienced in actionscript. I'm having an issue that should not be one, can't get my head around it.
In the code below all I want to do is pass a integer variable (stackID) as an img id attribute inside innerHTML. It must be some detail I just don't know but I have searched for hours on google to no avail. Help would be greatly aprreciated. Whatever I do, it seems I can only pass <img id="string">, which of course is not what I want. Can't pass <img id=numVariable>, or <img id=String(numVariable)>, there must surely be a way to do this ?
Thanks folks !
Here is the line of code :
div.innerHTML='<img src="img/xbut.png" id=String(stackID) onclick="close(this.id)">';

You're trying to pass it in the string.
What you want to do is:
div.innerHTML='<img src="img/xbut.png" id="' + String(stackID) + '" onclick="close(' + this.id + ')">';
Oh and since you're already making a string, you don't need the String() convert, you can just id="' + stackID + '"

Javascript is loosely typed and will automatically convert (to the best of its abilities) anything you want to interpolate in a string:
var num = 1;
"sup" + num; // => "sup1"
It's cool, but be careful though, it can lead to some weird surprises:
var obj = {};
"sup" + obj.missingKey; // => "supundefined"
In that case, obj.missingKey === undefined, and String(undefined) === "undefined", so "sup" + obj.missingKey becomes in fact "sup" + "undefined"

javascript has not string interpolation. Concatenate stackId like:
div.innerHTML='<img src="img/xbut.png" id="' + stackID + '" onclick="close(this.id)">';

Use '+' to join chunks like this:
div.innerHTML='<img src="img/xbut.png" id="' + String(stackID) + '" onclick="close(' + this.id + ')">';

Try this, you make the variable is dynamic:
var x = 0;
x = x +1;
div.innerHTML='<img src="img/xbut.png" id="name_' + x + '" onclick="close(this.id)">';

Related

How to change only the second parameter of an onclick function when it's clicked

I have an onclick handler with two parameters. When it's clicked I want to update only the second parameter value. I prefer jQuery.
I have tried all kinds of jQuery combinations.
The included code works but I want to exclude replacing the first parameter.
The link:
<a href="#" id="messageremove" onclick="messageremove('param1', 'param2')"
The jQuery code:
$("#messageremove").attr('onclick', 'messageremove(' + "'" + param1 + "'" + ', ' + "'" + param2_new + "'" + ')');
I want to exclude replacing the first parameter, but right now both are being replaced.
Pass the variables, store the before variable and the new variable. Then update accordingly. I just switched them in this exmaple.
let before = '';
let after = '';
function messageremove(param1, param2) {
before = param1;
after = param2;
$("#messageremove").attr('onclick', `messageremove(`+ after + `,` + before + `)`)
console.log($("#messageremove").attr('onclick'))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Switch

JS var inside query does not work when stringed together

I have the following code which is really bloated
$(".field-name-field-parts-status .field-item:contains('Submitted'), .field-name-field-parts-status .field-item:contains('Saved'), .field-name-field-parts-status .field-item:contains('HMNZ Approved')").addClass('btn-primary');
I tried to neaten it up by adding a var
var fieldItemStatus = $(".field-name-field-parts-status .field-item");
So it looked like this
$(fieldItemStatus + ":contains('Submitted'), " + fieldItemStatus + ":contains('Saved'), " + fieldItemStatus + ":contains('HMNZ Approved')").addClass('btn-primary');
But it stopped working, can anyone tell me what I did wrong? Thanks
Because you are trying to add a jQuery object and a string together. It does not work like that.
var fieldItemStatus = $(".field-name-field-parts-status .field-item");
should be a string
var fieldItemStatus = ".field-name-field-parts-status .field-item";
other option is to use filter.
You need to use .filter()
fieldItemStatus.filter(":contains('Submitted'), :contains('Saved'), :contains('HMNZ Approved')").addClass('btn-primary');
fieldItemStatus is an object so
fieldItemStatus + ":contains('Submitted'), " + fieldItemStatus + ":contains('Saved'), " + fieldItemStatus + ":contains('HMNZ Approved') will create a string like [Object object]:contains('Submitted'), [Object object]:contains('Saved'), [Object object]:contains('HMNZ Approved')
remove $ in front for fieldItemStatus
var fieldItemStatus = ".field-name-field-parts-status .field-item";
Because you want to use a jQuery Object to concat string. The right way to do this is using string all the time.
var fieldItemStatus = ".field-name-field-parts-status .field-item";
$(fieldItemStatus + ":contains('Submitted'), " + fieldItemStatus + ":contains('Saved'), " + fieldItemStatus + ":contains('HMNZ Approved')").addClass('btn-primary');
You could use the filter method:
fieldItemStatus.filter(":contains('Submitted'), :contains('Saved'), :contains('HMNZ Approved')").addClass('btn-primary');
Another option is using the filter callback function:
var items = ['Submitted', 'Saved', 'HMNZ Approved'];
fieldItemStatus.filter(function(_, el) {
return items.some(function(item) {
return el.textContent.indexOf(item) > -1;
});
});
.
A more procedural approach. This way if you want to easily change the selectors, just change the contains array. You could turn this into a function to easily retrieve your selector on demand elsewhere in the script.
var contains = ['Submitted','Saved','HMNZ Approved'];
var selector = '';
for(var i = 0; i < contains.length; i++) {
selector += '.field-name-field-parts-status .field-item:contains("' + contains[i] + ')';
if(i < contains.length - 1) selector += ', ';
}
$(selector).addClass('btn-primary');

JSON parse issue for duplicate data?

I'm constructing a JSON based on certain values,
my code is as follows,
var txt = '{ \"' + 9837 + '\": "Cost-A", \"' + 8943 + '\": "Cost-B", \"' + 13917 + '\": "Cost-C", \"' + 13917 + '\": "Cost-D"}';
_obj = JSON.parse(txt);
The output I get in the console is,
Object {9837: "Cost-A", 8943: "Cost-B", 13917: "Cost-D"}
Cost-C has been skipped completely? or is there something trivial I'm missing? How can I solve this?
Javascript ojects cannot have duplicate keys. Hence it gets overwritten.
{ "9837": "Cost-A", "8943": "Cost-B", "13917": "Cost-C", "13917": "Cost-D"}
The parser would add the latest value of the key.

How can I set .innerHTML equal to two variables

For simplicity, I'm not going to show too much code, but the variables are set, and the following code is within a conditional. I'm just trying to show the var _offsetX and var _offsetY at the same time.
window.document.getElementById('cssposition').innerHTML = _offsetX _offsetY;
try:
window.document.getElementById('cssposition').innerHTML = _offsetX +" " + _offsetY;
Just use the + operator:
window.document.getElementById('cssposition').innerHTML = "X=" + _offsetX + " Y=" + _offsetY;
concat these two variables? ...innerHTML = "" + _offsetX + _offsetY;
Concatenate two variables and then try out, but make a note this a redundant way,
window.document.getElementById('cssposition').innerHTML=_offsetX.concat(_offsetY);
Note: This ignores the space

Pass multiple parameters from ASP.NET to javascript function

Essentially what I'm trying to do is fairly simple....pass more than one parameter (4 total eventually) into a javascript function from my ASP.NET code behind.
What I've tried to do is this in the ASCX file...
function ToggleReportOptions(filenameText, buttonText) { /*stuff happens here*/ }
and this in the ASCX.cs file...
string testing123 = "testStringOne";
string testing124 = "testStringTwo";
optReportOptionsRunRealTime.Attributes["onClick"] = "ToggleReportOptions('" + testing123 + ", " + testing124 + "')";
optReportOptionsOffline.Attributes["onClick"] = "ToggleReportOptions('" + testing123 + ", " + testing124 + "')";
but this doesn't seem to work as in my output the first variable contains "testStringOne, testStringTwo" and the 2nd variable is "undefined"
Any help on clearing up my probably stupid issue here would be great (i'm very inexperienced with javascript, more of a .NET developer)
You've missed out a few single-quotes, meaning that you're passing a single string containing a comma rather than two separate strings. That is, you're passing 'testStringOne, testStringTwo' rather than 'testStringOne' and 'testStringTwo'.
Try this instead:
optReportOptionsRunRealTime.Attributes["onClick"] =
"ToggleReportOptions('" + testing123 + "', '" + testing124 + "')";
optReportOptionsOffline.Attributes["onClick"] =
"ToggleReportOptions('" + testing123 + "', '" + testing124 + "')";

Categories

Resources