Splitting out xml result into dropdownlist - javascript
Hope someone can help - I'm new to js/jQuery so I'm hoping it's something really simple I'm missing here.
I'm trying to populate a dropdownlist with the xml result from below. The parseXML function works great and the result.push(valueid + "," + value) leaves me with the following:
1,Service
2,Breakdown
How do I get this into a dropdownlist please? Using the below, I get the error "Object doesn't support property or method 'split'"
Many thanks
leddy
function testFunction() {
var jobresults = "<resultset morerecords='0'> " +
"<result> " +
"<itt_jobtypeid>1</itt_jobtypeid> " +
"<itt_name>Service</itt_name> " +
"</result> " +
"<result> " +
"<itt_jobtypeid>2</itt_jobtypeid> " +
"<itt_name>Breakdown</itt_name> " +
"</result> " +
"</resultset> ";
var xml = parseXML(jobresults);
var jobid = xml.getElementsByTagName("itt_jobtypeid");
var jobname = xml.getElementsByTagName("itt_name");
var result = [];
for (var i = 0; i < jobid.length; i++) {
var valueid = jobid[i].childNodes[0].nodeValue;
var value = jobname[i].childNodes[0].nodeValue;
// add longitude value to "result" array
result.push(valueid + "," + value);
}
var jobtype = $("#ddlJobType");
$.each(result, function () {
var arr = result.split(',');
for (var i = 0; i < arr.length; i++) {
jobtype.append($("<option />").val(arr[0]).text(arr[1]));
}
});
}
function parseXML(text) {
if (window.DOMParser) {
parser = new DOMParser();
doc = parser.parseFromString(text, "text/xml");
}
else { // Internet Explorer
doc = new ActiveXObject("Microsoft.XMLDOM");
doc.async = "false";
doc.loadXML(text);
}
return doc;
}
It can be simpler and cleaner if you optimize data structure for result array. Push an object with value and label so that you can simply use attr method directly after:
for (var i = 0; i < jobid.length; i++) {
var valueid = jobid[i].childNodes[0].nodeValue;
var value = jobname[i].childNodes[0].nodeValue;
// add longitude value to "result" array
result.push({value: valueid, label: value});
}
var jobtype = $("#ddlJobType");
$.each(result, function (i, obj) {
$('<option>').attr(obj).appendTo(jobtype);
});
See https://api.jquery.com/jquery.each/. The callback function gets each jobtype as parameter to the function.
Try changing the code to:
$.each(result, function (idx, value) {
var arr = value.split(',');
for (var i = 0; i < arr.length; i++) {
jobtype.append($("<option />").val(arr[0]).text(arr[1]));
}
});
Related
Nested loop only rendering last indexed item using jquery appendPe
Performing an ajax call to a drinks api and I've nested a loop to pull the ingredients out and render them to the page. The nested loop consoles the ingredients correctly but when I use jquery to append the results to the page only the item in the last index is displayed. I know there are null values I was going to remove them with an if statement after I got them to show. function displayDrinkData(drinkName) { var queryURL = "https://thecocktaildb.com/api/json/v1/1/search.php?s=" + drinkName $.ajax({ url: queryURL, method: "GET" }).then(function (response) { console.log(response); var results = response.drinks; for (var i = 0; i < results.length; i++) { console.log(results[i]); var eachDrink = results[i]; var drinkDiv = $("<div>"); var drinkName = results[i].strDrink; for (var k = 1; k < 16; k++) { console.log(eachDrink['strIngredient' + k]); var ingList = $("<ul>").text("Ingredients: " + eachDrink['strIngredient' + k]) } var pOne = $("<p>").text("Drink name: " + drinkName); var drinkInstructions = results[i].strInstructions; var pTwo = $("<p>").text("Instructions: " + drinkInstructions); var drinkImage = $("<img>"); drinkImage.attr("src", results[i].strDrinkThumb); drinkDiv.append(pOne); drinkDiv.append(ingList); drinkDiv.append(pTwo); drinkDiv.append(drinkImage); $("#drinks-view").append(drinkDiv); } }) }
Because var ingList is inside loop, not appending, but creating a new one every time. var ingList = $("<ul>"); for (var k = 1; k < 16; k++) { console.log(eachDrink['strIngredient' + k]); ingList.append($('<li>').text("Ingredients: " + eachDrink['strIngredient' + k])); } Declare variable outside loop, and append <li> for each element.
Loop using two related arrays
When a button is clicked i want the results in the array to be listed for example: John Smith 16, Jack Snow 10 etc.. I want to use a loop however the code in my loop is incorrect at the moment as when i click the button all i get is: [object Object]. Can someone provide a possible fix? function begin() { listresults(); (); } var results1 = {name:"John Smith", score:16}; var results2 = {name:"Jack Sow", score:10}; var results3 = {name:"Tessa Flip", score:15}; var results = [results1, results2, results3]; function listresults() { var text = ""; var total = 0; var i; for (i in results) { text += results[i] + "<br>"; } document.getElementById('message').innerHTML = text; }
I would first check that the lengths of the 2 arrays are the same. Then iterate using a for loop: final int timeLength = TIME.length; if (timeLength != stat.size()) { //something may not be right } for (int i = 0; i < timeLength; i++) { System.out.println(time[i]+" "+stat.get(i)); }
You are pushing objects results1, results2, etc in the array 'results'. So while iterating the array you should access the object properties as shown below: function listresults() { var text = ""; var total = 0; var i; for (i in results) { text += results[i]['name'] + ' ' + results[i]['score'] + "<br>"; }
As you are appending objects instead of object values in the filed. This is the proper way of accessing name and score from object which is returned when you are looping through your array of objects : function begin() { listresults(); (); } var results1 = {name:"John Smith", score:16}; var results2 = {name:"Jack Sow", score:10}; var results3 = {name:"Tessa Flip", score:15}; var results = [results1, results2, results3]; function listresults() { var text = ""; var total = 0; for (var i=0; i < results.length; i++) { text += results[i].name + " " + results[i].score + "<br>"; } document.getElementById('message').innerHTML = text; } Here is an Jsfiddle example
Recommend you to use Array methods(map, join) instead of pure loops function begin() { listresults(); } var results1 = {name:"John Smith", score:16}; var results2 = {name:"Jack Sow", score:10}; var results3 = {name:"Tessa Flip", score:15}; var results = [results1, results2, results3]; function listresults() { document.getElementById('message').innerHTML = results.map(function(item) { return item.name + ' ' + item.score; }).join('<br>'); document.getElementById('total').innerHTML = results.map(function(item) { return item.score; }).reduce(function(sum, score) { return sum + score; }, 0); } <button onclick="begin()">begin</button> <br /> <div id="message"></div> <div>total: <span id="total">0</span></div>
Use Array.map() and Array.join() var results1 = {name:"John Smith", score:16}; var results2 = {name:"Jack Sow", score:10}; var results3 = {name:"Tessa Flip", score:15}; var results = [results1, results2, results3]; var res = results.map(item => { return item.name+ " " +item.score }); console.log(res.join(", "));
Jquery ajax send json
Javascript: function add_content(count) { var result = {}; var row = new Array(); for (i = 0; i < count; i++) { result['img_src'] = $("#img_" + i).attr('src'); result['desc'] = $("#desc_" + i).val(); row.push(result); } $.ajax({ url: "ajax-functions.php", data: {json_data: JSON.stringify(row)}, type: 'post', success: function (output) { alert(output); } }) } Php: $img_desc = json_decode($_POST['json_data'],TRUE); $count = count($img_desc); echo 'count:'.$count; print_r($img_desc); I want to send json to from JS to PHP. This above code works well, but it send the last data of the for loop is set in all the objects. How to fix it? Is this right way? Thanks.
Push a new object on each round of the loop into to the array for (var i = 0; i < count; i++) { row.push({ "img_src": $("#img_" + i).attr('src'), "desc": $("#desc_" + i).val() }); } fiddle
Move result declaration inside for: var row = new Array(); for (i = 0; i < count; i++) { var result = {}; result['img_src'] = $("#img_" + i).attr('src'); result['desc'] = $("#desc_" + i).val(); row.push(result); } or it can be done more elegantly: var row = new Array(); var result; for (i = 0; i < 10; i++) { result = row[ row.push({}) - 1 ]; result['img_src'] = $("#img_" + i).attr('src'); result['desc'] = $("#desc_" + i).val(); }
You can make the keys of result array also dynamic Since you are not making it dynmamic, its getting over ridden in the next loop EDIT: for (i = 0; i < count; i++) { var result = {}; result['img_src'] = $("#img_" + i).attr('src'); result['desc'] = $("#desc_" + i).val(); row.push(result); }
Spliting String and getting appropriate value in JavaScript
I have a string where |||| means next to it is the directory. ||| means the user is allowed to access this directory and || means the files allocated to these users follow. I need to find allocated file names of a specific user from this string. I have tried to split the string and assign values to an array but I am not able to get the result I'm looking for. This is the string: ||||Root|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,||||1400842226669|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,testTask1_20140528135944.xlsx,testTask2_20140528140033.xlsx,||||1401191909489|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,testTask1_20140528135944.xlsx,testTask2_20140528140033.xlsx,LimitTest_20140528164643.xlsx, And here is my attempt: function getData() { var user = 'km11285c'; var value = "||||Root|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,||||1400842226669|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,testTask1_20140528135944.xlsx,testTask2_20140528140033.xlsx,||||1401191909489|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,testTask1_20140528135944.xlsx,testTask2_20140528140033.xlsx,LimitTest_20140528164643.xlsx,"; var users = null; var files = null; var Dir = value.split("||||"); var arrayLength = Dir.length; for (var i = 0; i < arrayLength; i++) { users = Dir[i].split("|||"); } return users; } console.log(getData()); and the jsFiddle
I changed your jsfiddle example a bit so maybe you need to change the code here and there, but something like this should work: function buildTree(data) { var tree = []; var dirs = data.split("||||"); // Remove the first entry in the array, since it should be empty. dirs.splice(0, 1); for (var i = 0; i < dirs.length; ++i) { var tempArray = dirs[i].split("|||"); var dirName = tempArray[0]; var usersAndFiles = tempArray[1]; tempArray = usersAndFiles.split("||"); var users = tempArray[0]; var files = tempArray[1]; var treeDir = { name: dirName }; treeDir.users = users.split(","); treeDir.files = files.split(","); tree.push(treeDir); } return tree; } function getData() { var user = 'km11285c'; var value="||||Root|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,||||1400842226669|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,testTask1_20140528135944.xlsx,testTask2_20140528140033.xlsx,||||1401191909489|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,testTask1_20140528135944.xlsx,testTask2_20140528140033.xlsx,LimitTest_20140528164643.xlsx,"; var tree = buildTree(value); for (var i = 0; i < tree.length; ++i) { var dir = tree[i]; if (dir.users.indexOf(user) >= 0) { console.log("User '" + user + "' has access to directory '" + dir.name + "', which contains these files: " + dir.files.join(",")); } } } getData();
generate list of variables from a FOR loop
var select = []; for (var i = 0; i < nameslots; i += 1) { select[i] = this.value; } This is an extract of my code. I want to generate a list of variables (select1, select2, etc. depending on the length of nameslots in the for. This doesn't seem to be working. How can I achieve this? If you require the full code I can post it. EDIT: full code for this specific function. //name and time slots function gennametime() { document.getElementById('slots').innerHTML = ''; var namelist = editnamebox.children, slotnameHtml = '', optionlist; nameslots = document.getElementById('setpresentslots').value; for (var f = 0; f < namelist.length; f += 1) { slotnameHtml += '<option>' + namelist[f].children[0].value + '</option>'; }; var select = []; for (var i = 0; i < nameslots; i += 1) { var slotname = document.createElement('select'), slottime = document.createElement('select'), slotlist = document.createElement('li'); slotname.id = 'personname' + i; slottime.id = 'persontime' + i; slottime.className = 'persontime'; slotname.innerHTML = slotnameHtml; slottime.innerHTML = '<optgroup><option value="1">00:01</option><option value="2">00:02</option><option value="3">00:03</option><option value="4">00:04</option><option value="5">00:05</option><option value="6">00:06</option><option value="7">00:07</option><option value="8">00:08</option><option value="9">00:09</option><option value="10">00:10</option><option value="15">00:15</option><option value="20">00:20</option><option value="25">00:25</option><option value="30">00:30</option><option value="35">00:35</option><option value="40">00:40</option><option value="45">00:45</option><option value="50">00:50</option><option value="55">00:55</option><option value="60">1:00</option><option value="75">1:15</option><option value="90">1:30</option><option value="105">1:45</option><option value="120">2:00</option></optgroup>'; slotlist.appendChild(slotname); slotlist.appendChild(slottime); document.getElementById('slots').appendChild(slotlist); (function (slottime) { slottime.addEventListener("change", function () { select[i] = this.value; }); })(slottime); } }
You'll have to close in the iterator as well in that IIFE (function (slottime, j) { slottime.addEventListener("change", function () { select[j] = this.value; }); })(slottime, i); and it's only updated when the element actually change
The cool thing about JavaScript arrays is that you can add things to them after the fact. var select = []; for(var i = 0; i < nameSlots; i++) { var newValue = this.value; // Push appends the new value to the end of the array. select.push(newValue); }