Setting HTML text using a loop - javascript

I'm currently running a REST query against a SharePoint list and I'm trying to display the results with a $().text() script. I have it working but would think there's a more efficient way. I have many fields I need to set but they're sequentially numerical and just think there should be a better way. Example below:
$('#div1Id').text(data.d.results[0].slot1);
$('#div2Id').text(data.d.results[0].slot2);
$('#div3Id').text(data.d.results[0].slot3);
Etc x20 fields...
I tried below, but I'm sure for reasons that are obvious to you all that know what you're doing this didn't work. The "divId" loads fine but the dataId shows the text "data.d.results[0].slot1"/2/3/etc instead of the actual data.d.results:
for (i=1;i<21;i++){
var divId = "#div"+i+"Id";
var dataId = "data.d.results[0].slot"+i;
$('+divId+').text(dataId);
}

Based on what your first example was doing, I think you want this:
for (i = 1; i < 21; i++) {
var divId = "#div" + i + "Id";
// access the value from the "slot#" property of the object
var data = data.d.results[0]['slot' + i];
// get the correct div based on the id and then
// set its text to the value
$(divId).text(data);
}

You could try the forEach method, or as already mentioned, get rid of the quotes in "data.d.results[0].slot"
var data = [{
"id": 1,
"Name": "Some Title 1",
"number": "Number 1"
}, {
"id": 2,
"Name": "Some Title 2",
"number": "Number 2"
}, {
"id": 3,
"Name": "Some Title 3",
"number": "Number 3"
}];
//data.d.results[0] << you'd use this
data.forEach(elem => {
document.getElementById("entries").innerHTML += elem.Name +"<br/>";
});
<div id="entries"></div>

Related

JS: Is it possible to make part of a variable dependent on the parameter of a function?

I'm really new to this and as such my terminology is probably poor, ask me for clarification if you need. Sorry if this is a basic question.
Here's an example of my problem:
var post1title = "example title 1";
var post1text = "example text 1";
var post2title = "example title 2";
var post2text = "example text 2";
function update() {
setText("titleBox", post1title);
setText("bodyBox", post1text);
My goal is to make the function update() have a parameter that allows the text in a text box to be either, for example, post1title or post2title.
I'd like to do something similar to what you do with strings when variables are involved, as shown here:
console.log("User has set the variable post1title to: " + post1title);
// prints "User has set the variable post1title to: example title 1" to the debug console
It doesn't seem like you can do the same thing when calling variables, though. I've tried doing the same as you would with strings (where "n" is a number 1-2):
var post1title = "example title 1";
var post1text = "example text 1";
var post2title = "example title 2";
var post2text = "example text 2";
function update(n) {
setText("titleBox", post + n + title);
setText("bodyBox", post + n + text);
This obviously reads as adding three variables together. Is something like this possible?
You can store the values as properties of a plain object or Map and use computed property names or bracket notation to get the corresponding value.
You can also adjust the order of the expected parameters.
const o = {
post1title: "example title 1",
post1text: "example text 1",
post2title: "example title 2",
post2text: "example text 2"
}
function update(p, t, n) {
console.log(o[p + n + t])
}
update('post', 'title', 1);
You could use an object with bracket notation to do something similar to this. This way your object will hold keys, which point to their associated values.
See example below:
var options = {
post1title: "example title 1",
post1text: "example text 1",
post2title: "example title 2",
post2text: "example text 2"
}
function update(n) {
setText("titleBox", options["post"+ n + "title"]);
setText("bodyBox", options["post" + n + "text"]);
}
function setText(id, txt) {
document.getElementById(id).textContent = txt;
}
update(1)
<h2 id="titleBox"></h2>
<p id="bodyBox" ></p>
Or, an alternative way would be to use a constructor function like so:
var post1title = "example title 1";
var post1text = "example text 1";
var post2title = "example title 2";
var post2text = "example text 2";
function update(n) {
setText("titleBox", Function("return post"+ n + "title")());
setText("bodyBox", Function("return post"+ n + "text")());
}
function setText(id, txt) {
document.getElementById(id).textContent = txt;
}
update(1);
<h2 id="titleBox"></h2>
<p id="bodyBox" ></p>
It's an anti-pattern to say the least, but if you really want to do this (and you don't, but alas):
function update(n) {
setText("titleBox", eval("post" + n + "title"));
...
...and, It has higher performance than using a Function() constructor. Still, eval() is bad practice.
It might be better to convert your variables into an object. This structure simulates the best for real-life data fetched from database for example. And I am using Template Literals inside the console.log for combining string and variables in an easier way
var posts = {
"title": {
"1": "example title 1",
"2": "example title 2",
},
"text": {
"1": "example text 1",
"2": "example text 2",
}
}
function update(part, n) {
/* setText("titleBox", post1title);
setText("bodyBox", post1text); */
console.log(`User has set the variable post${n}${part} to: ${posts[part][n]} `);
}
update('title', '1')
update('title', '2')
update('text', '1')
update('text', '2')

Angular2 displaying a particular Questions from the JSON for the selected dropdown values after finding a proper match

I have a dropdown which has numeric values like 1 and 2. In my JSON, I have a "filters" attribute which is an array. The requirement is:
Whenever I select any value from the dropdown — let's say I have selected 2 in the dropdown — then I want to check if the selected value is equal to any of the "answer" attribute in the "filters" array whose value is same as the selected value, i.e 2.
If more than one object has the same answer value, it should check if the "code" matches the "questionCode" of "filters` array for the selected match. If yes, then the respective "displayKey" should be displayed.
My JSON:
{
"code": "abc",
"displayKey": "question1",
"filters": [{
"questionCode": "abc",
"answer": "2"
}],
"order": 9,
"industryList": {}
},
{
"code": "pqr23",
"displayKey": "question2",
"filters": [{
"questionCode": "gthy67",
"answer": "1"
}],
"order": 2,
"industryList": {}
},
{
"code": "abc",
"displayKey": "question3",
"filters": [{
"questionCode": "abc342",
"answer": "2"
}],
"order": 9,
"industryList": {}
}
In my .ts file:
for(var i=0; i<=this.questions.filters.length;i++ ){
var questionsObj = this.questions.filters[i];
//psuedoCode
if(this.selectedValue == questionsObj.answer){
if(this.questions.code == questionsObj.questionCode ){
this.displayFilterCode = true;
}
else{
this.displayFilterCode = false;
}
}
}
My JSON is very big and i am saving the entire object in a questions object. I have just added the required bit here.
In my HTML:
<dropdown [(ngModel)] = "selectedValue"></dropdown>
My dropdown is populating properly on the page but not sure why the respective questions are not being displayed. Can anyone let me know what I am doing wrong and how can I get the questions displayed. I am not sure if I am following the right approach but I am trying out this way. Also, I am getting error as length undefined (not sure why). Since filters is an array so filters.length should work.
well you are not accessing your json properly.
this is what you should try
for(var i=0; i<=this.questions.length;i++ ){
var questionsObj = this.questions[i];
//now one question from question array is assigned to questionobj
if(this.selectedValue == questionsObj.filters[0].answer){// your answer is in questionsObj.filters[0].answer position
if(this.questions[i].filters[0].questionCode == questionsObj.filters[0].questionCode ){
this.displayFilterCode = true;
}
else{
this.displayFilterCode = false;
}
}
let me know if you still face any error. because i don't know from where you are getting this.seletedValue.

Read JSON data from javascript and trim string

I have json file like this,
{
"data":{
"type": "runjob",
"id": "1",
"inputs": [
{
"name": "input",
"value": "d:\\My\\filestore\\JMJ\\Content\\input.xml"
},
{
"name": "cmd",
"value": "test.js //NoLogo"
},
{
"name": "output",
"value": "d:\\My\\filestore\\JMJ\\Content\\output.xml"
}
],
"disabled": false
}
}
I need to read the velues, input.xml and output.xml using javascript.. How can I get those value?
var stdin = WScript.StdIn.ReadAll();
var json = eval('(' + stdin + ')');
var log = new Log(json.data.inputs[?]);
json.data.inputs is an array (note it's json; as Tushar pointed out, you have had jason in the question). So you can use any technique for accessing or looping through an array that's supported by your environment. It look slike you're using JScript on Windows Script Host; last I checked it didn't even have ES5 features, so perhaps a simple for loop:
var i;
var inputs = json.data.inputs;
for (i = 0; i < inputs.length; ++i ){
// Here, inputs[i].name will be the name ("input", "cmd", "output")
// and inputs[i].value will be the value ("d:\\My\\filestore\\JMJ\\Content\\input.xml", for instance)
}
json.data.inputs is an array containing 3 json objects; you want the value property of the first and the third elements:
json.data.inputs[0].value; // "d:\\My\\filestore\\JMJ\\Content\\input.xml"
json.data.inputs[2].value; // "d:\\My\\filestore\\JMJ\\Content\\output.xml"

javascript/jquery: on click copy relevant array items to new array

I think I'm missing an obvious answer. I have an array of arrays, like this
var arraylist = [
{
"id" = 0,
"title" = "title number 1",
"info" = "some info etc 1"
},
{
"id" = 1,
"title" = "title number 2",
"info" = "some info etc 2"
},
]
...etc. And a function that makes some html from each array, which is appended to a ul element.
function makeBox(){
for (i = 0; i < arraylist.length; i++ ) {
var boxHTML = '<li id="' + arraylist[i].id + '">'
+ '<div>' + arraylist[i].title + '</div>'
+ '</li>'
$('ul').append(boxHTML);
};
};
Now using a click function, on clicking the 'li' I want the relevant array from arraylist to be copied to a new array.
newArrayList = []
So clicking on li #0 would copy the first array from 'arraylist' to the 'newArrayList'.
I will then be making different HTML from 'newArrayList' using different values. So in the makeBox function I won't show the value "info", but when I make HTML from newArrayList I will.
I could use innerHTML to get the data back out of the HTML to the newArrayList, but would have to append "info" to a hidden span, or something. This seems like the long way round. So what's the easy way?
I'm just learning so go easy on me. Also did a good search and couldn't find the answer. If it's already there please direct me politely.
So a few notes:
It's not an array of arrays. It's an array of objects. The [ ] block
is an array. The { } is an object.
The $('ul') will select ALL uls on the page, not necessarily just the
one you intend.
The object structure is incorrect, it should be using colon (:) rather
than equal (=) characters. It should look more like this:
var arraylist = [{
"id": 0,
"title": "title number 1",
"info": "some info etc 1"
}, {
"id": 1,
"title": "title number 2",
"info": "some info etc 2"
}]
Here is a modified version of your function.
function makeBox(){
var $ul = $('ul.from_array_one');
for (var i = 0; i < arraylist.length; i++) {
var item = arraylist[i];
var $boxHTML = $('<li id="' + item.id + '">' + item.title + '</li>');
$boxHTML.click(onSelectItem(item));
$ul.append($boxHTML);
};
};
Where a new function exists accepting the array object item, such as:
function onSelectItem( item ){
return function(){
var $ul2 = $('ul.from_array_two');
var $boxHTML2 = $('<li id="' + item.id + '">' + item.info + '</li>');
$ul2.append($boxHTML2);
}
}
Shaun's solution should work when implemented correctly (one point for your effort).
Here is another way.
I modified your (OP's) function so can be reused for other array of same types. Since you're learning, I encourage you to read up on DRY principle a.k.a. "don't repeat yourself". Adhering to this principle while designing your code, will help you write code that is more reusable resulting in shorter code, in the longer run a more maintainable code base. And in the process you will become an even better coder.
var arraylist = [
{
"id": 0,
"title": "title number 1",
"info": "some info etc 1"
},
{
"id" : 1,
"title": "title number 2",
"info": "some info etc 2"
},
];
var newArrayList = [];
///
function makeBox(arrayToMake, ulToAppendTo, liClass){
for (i = 0; i < arrayToMake.length; i++ ) {
var boxHTML = '<li class="'+liClass+'" id="' + arrayToMake[i].id + '">'
+ '<div>' + arrayToMake[i].title + '</div>'
+ '</li>'
$(ulToAppendTo).append(boxHTML);
};
};
var firstListClass = "first_list_item";
var secondListClass = "second_list_item";
makeBox(arraylist,'.ul_one',firstListClass);
$("."+firstListClass).click(function(){
copyArray(arraylist,newArrayList);
makeBox(newArrayList,'.ul_two',secondListClass);
});
function copyArray(sourceArray, targetArray)
{
sourceArray.forEach(function(item){
//for demo purpose only
item.title="new title " + item.id;
targetArray.push(item);
});}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>first array result</p>
<ul class='ul_one'></ul>
<p>new array result</p>
<ul class='ul_two'></ul>

Looping over JSON object returning undefined for some elements

In my JSON object in posts.php I have two arrays, posts and comments. Here's an example (posts is just [...] for this example but comments has 2 example comments:
posts.php
{
"posts": [{
...
}],
"comments": [{
"id": "1",
"submitter": "",
"time": "1433601171",
"comment": "example comment",
"score": "0",
"postid": "1"
}, {
"id": "2",
"submitter": "",
"time": "1433601211",
"comment": "another comment",
"score": "0",
"postid": "1"
}]
}
Javascript:
$.getJSON('posts.php',function(data){
data.comments.forEach(function(comment){
var id = comment.id;
var submitter = comment.submitter;
var time = comment.time;
var comment = comment.comment;
var score = comment.score;
var postid = comment.postid;
For some reason when I alert(score) and alert(postid) they are undefined, yet all the other variables contain the correct information. Why?
You having the same variable name of comment
//original comment variable points to commnet.comment
var comment = comment.comment;
//comment get overwrite from the original commnet
//now comment points to comment.comment
var score = comment.score;
var postid = comment.postid;
This causes score and postid to be undefined, because now you are referring score as comment.comment.score which is undefined
for some reason javascript does not like the variable name "comment" in the function parameter, because you use it twice.
If you rename the variable to c for example, it works.
data.comments.forEach(function(c){
var id = c.id;
var submitter = c.submitter;
var time = c.time;
var comment = c.comment;
var score = c.score;
var postid = c.postid;
})
It is happening because you are using same variable named comment for different purposes.
var cmt = comment.comment;
Statements accessing comment as object after statement
var comment = comment.comment;
will throw error.
Change variable name comment inside loop, and it will be working.
DMEO here.

Categories

Resources