Ok this must have a simple solution but I'm breaking my head over this one...
I have a js code which picks up ID numbers from my HTML by class. It stores all in an array. I checked that the array is not undefined and is not empty. Sofar so good.
Now I need to get this array of ID's to display into an HTML element. The full array should just come out as a comma separated string.
The piece of code which is relevant:
function makelink(){
var idArray = $(".result");
document.getElementById("link").innerHTML = idArray;
}
//The result in HTML = [object Object]
When I do the following it works exactly as I want (except that I can't hardcode the array into the code like this of course)
function makelink(){
var idArray = ["123", "124", "125", "126"];
document.getElementById("link").innerHTML = idArray;
}
//The result in HTML = [123,124,125,126]
I read at least 4 other similar questions on Stackoverflow such as What does [object Object] mean? and Convert javascript array to string and based on that I tried:
document.getElementById("link").innerHTML = idArray.join();
and also:
var idArray = $(".result");
idArray.toString();
but I could not figure out how to make it work for my code. I don't need to alert or console.log. I need my result to be output in the HTML. Please help.
You can try this:
function makelink(){
var idArray = [];
$(".result").each(
function(){
idArray.push($(this).text())
}
);
document.getElementById("link").innerHTML = idArray.join(', ');
}
You are not displaying the array, but the jQuery object of the DOM element. You might need the map function. But this function is not enough by itself, you will still need to get the value of the result object, or the html, but that part is the easiest.
function makelink(){
var idArray = $(".result").map(function(item) {
return item.val();
}).get();
document.getElementById("link").innerHTML = idArray;
}
Do this ::
function makelink() {
var idArray = ["123", "124", "125", "126"];
document.getElementById("link").innerHTML = JSON.stringify(idArray);
}
Related
I have tried everything and I can not split a PHP variable into two parts so I can insert them into two input fields. I have read numerous topics here and I don't see the problem...
This peace of code gives me a result that php variable is inserted into a wanted filed.
Lets say the PHP variable is data1-data2:
document.hiderad.selectstate.onchange = updateText;
function updateText() {
var str = document.hiderad.selectstate;
document.hiderad.opis.value = str.value;
}
Code above inserted data1-data2 into wanted HTML input.
And soon as i try to split it i get undefined warning. I have tried 7 different things to approach this problem so i want even list all the versions I tried. Can someone please help?
document.hiderad.selectstate.onchange = updateText;
function updateText() {
var str = document.hiderad.selectstate;
var array = str.toString().split('-');
a = array[0], b = array[1];
document.hiderad.opis.value = a.value;
document.hiderad.iznos.value = b.value;
}
Code above gives me b undefined if i remove last line i get a undefined.
You shouldn't be using a.value and b.value, that's for getting the value of an input field, not a string. You should use that to get the value of the selectstate input.
Also, always declare local variables unless you have a specific reason to assign global variables.
function updateText() {
var str = document.hiderad.selectstate;
var array = str.value.split('-');
var a = array[0], b = array[1];
document.hiderad.opis.value = a;
document.hiderad.iznos.value = b;
}
I have some JSON data which contains some urls. I'm extracting these urls from the json by looping through the objects which works fine. The urls however have 'page: ' pre-pended to them which i am trying to replace with 'https://'.
I can't get the replace property to work and give me the same result each time.
I've tried using the replace() property in different way and am using the console.log to view my results. I've also tried to stringify the JSON as I hear this is a good thing to do in order to handle it.
Each time i'm still seeing the 'page: ' word and it hasn't been replaced.
function showTopArticles(jsonObj) {
var getEntries = jsonObj.feed.entry;
var stringified = JSON.stringify(getEntries);
console.log(getEntries);
for (var i = 0; i < getEntries.length; i++) {
var list = document.createElement('article');
var articleTitle = document.createElement('li');
var articleUrl = document.createElement('a');
articleTitle.textContent = getEntries[i].title.$t;
articleUrl.textContent = getEntries[i].content.$t;
articleUrl.textContent.replace("page: ", "https://");
console.log(articleUrl.textContent);
list.appendChild(articleTitle)+list.appendChild(articleUrl);
section.appendChild(list);
}
}
I expect the output url to be 'https://www.google.com' but instead im seeing 'page : www.google.com'
replace() returns a modified value, it does not modify the original string.
You want something like:
articleUrl.textContent = articleUrl.textContent.replace("page: ", "https://");
I have the below code, which loops through the DOM looking for elements that have an id starting with "sale-", with an attribute "data-id", capturing the value, then stripping the opening and closing square brackets - pushing it all into a JSON object:
els = $("div[id^='sale-']");
Array.prototype.forEach.call(els, function(el) {
var id = el.attributes[2].value.replace(/\[|\]/gi, "");
var jsonObject = {"id" :+id};
var myJSON = JSON.stringify(jsonObject);
console.log(myJSON+",")
});
This works and the output is:
Now the problem comes when I want to apply some static JSON code before and after the loop.
I would like something like the below:
// static
dataLayer.push({
'ecommerce': {
'impressions': [
// loop portion
{"id":50450},
{"id":49877},
{"id":49848},
{"id":49912},
{"id":49860},
{"id":49825},
{"id":48291},
{"id":49667},
// static
]
}
});
Firstly you can make the array creation much more simple by calling map() on the jQuery object. From there you can simply add the resulting array to an object with the required structure. Try this:
var idArr = $("div[id^='sale-']").map(function() {
var id = this.attributes[2].value.replace(/\[|\]/gi, "");
return { id: +id };
}).get();
dataLayer.push({
ecommerce: {
impressions: idArr
}
});
Also note that this.attributes[2].value can be improved, but you haven't stated which attribute you're expecting that to target.
Followup question from here: Old question
This result come from other file script called localStorage.result
output is: [{"url_field":"yahoo","enabled":true},{"url_field":"google","enabled":true},{"url_field":"bing","enabled":true}]
To extract specific ID/value I use this code:
var myurlsave = localStorage.result;
var arr = myurlsave.map(function(a) {
return a.url_field;
});
This code above has no result or output. But when I write manually the result of localStorage.result like this:
var myurlsave = [{"url_field":"yahoo","enabled":true},{"url_field":"google","enabled":true},{"url_field":"bing","enabled":true}];
var arr = myurlsave.map(function(a) {
return a.url_field;
});
There will be a result that I need: var arr = ["yahoo", "google", "bing"]
But I need to use the var myurlsave = localStorage.result because this dynamical change base on users input.
Thank you for the help
From the looks of your logic it would appear that localStorage.result is a string. In this case you need to deserialise it to an object:
var myurlsave = JSON.parse(localStorage.result);
var arr = myurlsave.map(function(a) {
return a.url_field;
});
How am I able to write this so that I do not change the order of myApp.myArr2 and only refer to it instead?
I want the 2nd last line to produce 'hello world' and the last line to produce 'world hello'
myApp.myArr2 = ["hello", "world"];
function reverseArray(temp) {
myApp.myNewArr2 = temp.reverse();
};
reverseArray(myApp.myArr2);
console.log(myApp.myArr2); // world hello
console.log(myApp.myNewArr2); // world hello
Try this:
Change the line from:
myApp.myNewArr2 = temp.reverse();
to
myApp.myNewArr2 = temp.slice().reverse();
A JSFiddle link example is here.
Best of luck.
Array.prototype.reverse make reverse array in-place. This is true. If you want to get copy you can do it with following code:
function reverseCopy(array) {
var copy = [];
array.forEach(function(e) { copy.unshift(e); });
return copy;
}
To get a copy of an array you can do:
var newArray = oldArray.slice();