How to create list in HTML dynamically? - javascript

In my jQuery mobile app, I want to display the result from a web service in a list. How do I create the list dynamically?

var arr = ["list", "items", "here"];
$("div").append("<ul></ul>");
for(var i in arr) {
var li = "<li>";
$("ul").append(li.concat(arr[i]))
}

Better yet,
$.each(
a ,
function(i,v) {
$("#target_id").append("<li>" + v + "</li>") ;
}
) ;
Where a is an Array of Objects for the list content, i is the index variable passed to the callback function by jQuery.each ($.each) and vis the value for that index.
For reference: http://api.jquery.com/jQuery.each/ .

Related

FInd object in array by value and update entire object

I have a list of objects and sometimes I receive an update from the API for one of those objects and what I need to do is to find the object with the id of the one to update and update the entire object...
I was trying to avoid a for loop because the list could be very very long.
So what I was trying to use is $.grep but it doesn't seem to work as expected.
Here is what I tried so far:
// item is the response data from the API
var item = res.item;
var index = $.grep(arrayOfItems, function (e, i) {
if (e.id === item.id) {
return i;
}
});
arrayOfItems[index] = item;
the item is not updated unfortunately...
If it's speed you're after, especially with a long list, you may consider indexing your list by id when you first retrieve it, making updates later quicker than having to loop the entire array to find an index.
To demonstrate, assume you have retrieved an array of objects
var data = [
{id:1,data:'hello'},
{id:2,data:'world'},
{id:3,data:'foo'},
{id:4,data:'bar'}];
now create an object which represents your data where the property is the Id (object properties cannot start with a number, so if id is numeric, prefix it) and the value is the index back into the original array. So, the above data would be transformed to
var dataIndex = {
id1:0,
id2:1,
id3:2,
id4:3
};
This can be done trivially with a function
function indexDataById(data)
{
var index = {};
$.each(data, function(e,i){
index['id' + e.id] = i;
});
return index;
}
var dataIndex = indexDataById(data);
Now, when it comes to your update, you can find the index instantly using the id
var updateId = 2;
var elementIdx = dataIndex ['id' + updateId];
data[elementIdx] = myNewData;
The one complication is that you need to go back and update the index if the id of the new data has changed:
var updateId = 2;
var elementIdx = dataIndex [`id` + updateId];
data[elementIdx] = myNewData;
delete dataIndex[elementIdx]
dataIndex['id' + myNewData.id] = elementIdx;
This should be easy enough to handle atomically with your update.
$.map and $.grep return both an array so you will never get the index.
Inside $.map or $.grep function you need to return true or false based
on your filter logic. They re not useful in your case.
if your structure is not ordered you can only loop trough it and stop the loop when you find your element... like that:
var item = res.item;
var index = "";
$.each(arrayOfItems, function(i,v){
if(item.id == v.id){
index = i;
return true;
}
});
arrayOfItems[index] = item;
if you wanna order your structure before loop use this:
arrayOfItems.sort(function(a, b) {
return a.id > b.id;
});
i ve made a fiddle with an example https://jsfiddle.net/L08rk0u3/
try this way using $.grep
var arrList = [
{name :11,id :11},{name :12,id :12},{name :111,id :111},
{name :13,id :13},{name :15,id :15},{name :11,id :11},
{name :41,id :41},{name :31,id :31},{name :81,id :81},
{name :91,id :91},{name :13,id :13},{name :17,id :17},
{name :1111,id :1111}
]
console.log(arrList);
var respItem ={name :1111000,id:1111};
var intSearchedIndex;
$.grep(arrList,function(oneItem,index){
if(respItem.id==oneItem.id){
return intSearchedIndex = index;
}
})
arrList[intSearchedIndex] =respItem;
console.log(intSearchedIndex,arrList);
Try with map method like this.
Code snippets:
// item is the response data from the API
var item = res.item;
var index = $.map(arrayOfItems, function (e, i) {
if (e.id === item.id) {
return i;
}
});
if(index.length)
arrayOfItems[index[0]] = item;
Update:
arrayOfItems[index] = item;
This will work if index array has an single element. See fiddle
But,
arrayOfItems[index[0]] = item;
This is the appropriate way since it is an array.

jQuery get json data, match the ids, then append the custom field value

I am trying to retrieve json data from zendesk, then compare the value of the ids in each ticket that is retrieved from the server with the id inside my table data. If the ids match, then I want to retrieve the custom field value inside the ticket with the matching id, and append it to the table data's that i have named with the product id. The idea is to target each "td/td",and automatically insert the custom field(product id) value when a new "td/td" tag is created. Please help :) The Object 99 at the top is the ticket, the id :175 is the id I am trying to match. the custom_field array[10] value is what I want to append and display. The issue I am having is that the data is not displaying after I append it. I think this has something to do with how I am accessing the data, comparing the ids, then appending the custom field. The array value is returning a -1 instead of comparing the IDs. This is the problem.
//first lets get some json data!
var getjson = $.getJSON("/api/v2/tickets.json)",function (result) {
$.each(result, function(i, field) {
console.log('data',field);
// now lets take the text id for each td and assign it as the id.
$(".sort > tr > td:nth-child(1)").each(function(){
var textid = $(this).text();
$(this).attr('id', textid);
// if the ids match, give me the value of the custom field that is inside the array of the matching id.
var arr = [field];
var arrayvalues = $.inArray('id', arr);
if ($(this).attr('id') == arrayvalues){
/* if the ids match, give me the value of the
custom field that is inside the array of the matching id. */
var returns = $.inArray('value',arr.custom_fields[i]);
// now for each td lets append the value of the custom field.
$(".sort > tr > td:nth-child(7)").each(function () {
$(this).append(returns);
$(this).attr('id','product');
})
}
})
});
See $.inArray usage described at documentation
jQuery.inArray( value, array [, fromIndex ] )
value
Type: Anything The value to search for.
array
Type: Array An array through which to
search. fromIndex Type: Number The index of the array at which to
begin the search. The default is 0, which will search the whole array.
Note, also $.inArray()
Returns: Number
Not certain about return value from $.getJSON ? full json not appear at original post ? , though see
$.getJSON("/api/v2/tickets.json}"
right bracket before closing double-quotation mark at url ?
Try changing js at
var arrayvalues = $.inArray(field).id;
and
var returns = return $.inArray(field).custom_fields('value');
to usage described at documentation, e.g.,
var arr = ["a", "b", "c"];
console.log(
$.inArray("a", arr) // `0`
, $.inArray("b", arr) !== -1 // `true`
, $.inArray("c", arr) === 3 // `false`
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
I figured it out after days of knocking my head against the wall. The following code works perfectly.
var Obj1 = {};
var Obj2 = {};
var Obj3 = {};
var urlstring = "/api/v2/tickets/"+id+".json)";
$.getJSON(urlstring,function (result) {
$.each(result, function(i, value) {
Obj1[result[i].id] = result[i].fields[10].value;
Obj2[result[i].id] = result[i].fields[13].value;
Obj3[result[i].id] = result[i].fields[7].value;
console.log('Obj1', Obj1);
console.log('Obj2', Obj2);
console.log('Obj3', Obj3);
});
$.each(Obj1, function(key, element) {
$(".sort > tr").each(function(){
if($(this).attr('id') == key){
$(this).children('td:nth-child(7)').append(element);
}
});//end tr each
}); //end obj1 each
$.each(Obj2, function(key, element) {
$(".sort > tr").each(function(){
if($(this).attr('id') == key){
$(this).children('td:nth-child(8)').append(element);
}
});//end tr each
}); //end obj2 each
$.each(Obj3, function(key, element) {
$(".sort > tr").each(function(){
if($(this).attr('id') == key){
$(this).children('td:nth-child(6)').append(element);
}
});//end tr each
}); //end obj3 each
});//end json

Use html() as append()

I want to use html() same as how it works with append()
function showResponse(response) {
var $list = $('#list');
var items = response.items;
$.each(items, function(id, el){
$list.html('el.id.videoId')
});
}
I dont know if anyone did understand it but what i want is
List1 = id1, id2 id3
List2 = id4 id5 id6
When List1 is listed, and List2 will be requested this must remove List1 and list List2
With append it makes the list just longer, but i want it to replace it with current
jQuery's html() replaces all the content every time you call it, so you're replacing the content on every iteration.
To only replace the content after the loop has completed you can do
function showResponse(response) {
var $list = $('#list');
var items = response.items;
var result = "";
$.each(items, function(id, el){
result += el.id.videoId;
});
$list.html(result);
}
Try this:
$list.html($list.html() + 'el.id.videoId');
jQuery.html() returns the current html in object
jQuery.html( data ) sets object html to data
Not sure why you want to use html() when append will do the job.
Empty the list it and append the new elements
$list.empty();
$.each(items, function(id, el){
$list.append("<li>" + id + "</li>");
});
If you want to use html(), than build a string with all the list items and set it at once.
Have you tried?
$list.empty().append('el.id.videoId');

Log input into array, print only new input

Okay I have a a couple of functions. I don't think most of them are relevant. What I want to do is create an html list when you click a button, and store the value in an array. However I want to be able to update this list without outputting the entire array again. I have it set up to accept the input and I can get it to loop and print the array but it will print the entire array and I only want one. This seems like a common thing but my Google-fu returned nothing.
So I have a list variable that connects to an input, logs it into an array, and another function to clear it and print out the values.
Code snippet:
var listItemInput= document.getElementByID("listItem");
var listItem= [];
function insertListItem(){
listItem.push(listItemInput.value);
clearAndShow();
}
function clearAndShow(){
listItemInput.value= "";
}
function printList{
for (var i = 0; i < listItem.length; i++){
document.getElementById("list").innerHTML += '<li>' + listItem[i] + '</li>';
}
When the printList funciton is called by pressing the button it prints the entire array over however I would like a button that simply prints the newest item. How could I do that?
For clarification, I need to print out the list to html and store the values in an array, the values will later be referenced in an if else argument to combine and print them with new variables.
EDIT:
I plugged in the var = lastIndex and changed it as well as made two more variables for my list. This seems to make it work. Thank you.
You could keep track of the last index printed.
var listItemInput= document.getElementByID("listItem");
var listItem = [];
var lastIndex = 0; //Keep track of the last index shown.
function insertListItem() {
listItem.push(listItemInput.value);
clearAndShow();
}
function clearAndShow() {
listItemInput.value = "";
}
function printList() {
for (; lastIndex < listItem.length; lastIndex++) {
document.getElementById("list").innerHTML += '<li>' + listItem[lastIndex] + '</li>';
}
}
This approach assumes you won't be removing items from listItem array, which you didn't express is something that would be done.
If you only want one element, why do you need to iterate?
function printList() {
document.getElementById('list').innerHTML = '<li>' + listItem[listItem.length-1] + '</li>';
}

Populate dropdown select with array-with multiple options

So I'm trying to populate a dropdown with the states, the value for the option should be the two characters value, and the text for the option should be the full state's name, using the code below is returning a value of 0,1,2,3... and returning all the options in the var as the text.
var states = ["Select State","","Alabama","AL","Alaska","AK","Arizona","AZ","Arkansas","AR",...];
$.each(states, function(val, text) {
$('#selector').append( $('<option> </option>').val(val).html(text) )
});
Try this, using an object for states instead of an array. Same results, but it's more clear what's what and you're less likely to have problems if you accidentally skip a name or abbreviation:
var states = {
"Select State":"",
"Alabama":"AL",
"Alaska":"AK",
"Arizona":"AZ",
"Arkansas":"AR"
};
var val, text;
for (text in states) {
val = states[text];
$('<option/>').val(val).text(text).appendTo($('#selector'));
};
http://jsfiddle.net/g59U4/
The problem is that the callback function provided to .each results in val containing the index of the current iteration (e.g. 0, 1, 2 etc.) and text containing the value of that index of the array.
To achieve what you are trying to, you would probably be better off with a normal for loop:
for(var i = 0; i < states.length; i+=2) {
$("#selector").append($('<option> </option>').val(states[i+1]).html(states[i]));
}
You would be even better off caching the jQuery object containing #selector outside of your loop, so it doesn't have to look it up every iteration.
Here's a working example of the above.
Another option would be to use an object instead of an array, using the state name or abbreviation as the keys, and the other as the values. Edit: just like #mblase75 has done
Well you have the jQuery.each function arguments confused. The first is the index of the value in the array, and the second in the value itself. What you need to do is something like:
$.each(states, function(index) {
if(index%2 > 0) {
//continue, basically skip every other one. Although there is probably a better way to do this
return true;
}
$('#selector').append( $('<option> </option>').val(states[index+1]).html(states[index]) )
});
That would be really straightforward if your array had two dimensions. Considering you really need to use the one-dimensional array you presented, you could do this:
var states = ["Select State","","Alabama","AL","Alaska","AK","Arizona","AZ","Arkansas","AR"];
for(var i=1; i<states.length; i+=2) {
$('#selector').append( $('<option value="' + states[i] + '">' + states[i-1] + '</option>').val(val).html(text) )
}
If you changed your array to be an array of objects, you could do something like this -
var states = [{"text":"Select State","val":""},{"text":"Alabama","val":"AL"}]; //etc
$.each(states, function(val, statedata) {
$('#selector').append( $('<option> </option>').val(statedata.val).html(statedata.text) )
});
This change passes a JavaScript object in to the callback each time. The object has text and val properties and is passed in to the callback as the statedata parameter. The val parameter holds the current index position of the array so it is not required to populate the select box.
Demo - http://jsfiddle.net/sR35r/
I have a similar situation populating a select list with a two-dimensional array as the result of an $.ajax callback ....
JSON ...
[["AL","Alabama"],["AK","Alaska"],["AS","American Samoa"],["AZ","Arizona"] ...
var stateOptions = $('#state');
var html ='';
for (var i =1; i<data.length; i++){
html+= '<option value="' +data[i][0]+ '">' +data[i][1]+ '</option>';
}
stateOptions.append(html);
<form name="form" id="form">
<select name="state" id="state">
<option value=''>State</option>
</select>
</form>

Categories

Resources