The code below is supposed to complete the following tasks once the first and last name fields are entered:
Assign the index number to the person,
Populate that information in a list form
Below is the code that I have so for:
$("volunteerList").value = null;
for(var i = 0, vString = i + 1 + ". " + volunteerArray[i] + "\n"; i < volunteerArray.length; i++){
$("volunteerList").value+=vString;
}
The problem that I am having is that it is not clearing out and no matter what the next name I enter is, it populates the same name as the first entry.
I'm not sure what I am missing from this code to allow for the next person to be entered with the next index number that follows, in this case, either 2, 3, 4, etc.
Any help is greatly appreciated.
You can use the map off of jQuery or the Array to build the list of strings you want to set as the value, and join them on empty string.
var volunteerArray = [ 'Jim', 'Sarah', 'Lance' ];
$("#volunteerList").val($.map(volunteerArray, function(element, index){
return ++index +'. '+ element +'\n';
}).join(''));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="volunteerList"></textarea>
The problem is your loop. You're setting the value for vString during the initialization of the for loop, so it does not get updated each iteration.
$("volunteerList").val() = null;
for(var i = 0; i < volunteerArray.length; i++){
vString = i + 1 + ". " + volunteerArray[i] + "\n"
$("volunteerList").val($("volunteerList").val() + vString);
}
Are you missing an id or class specifier in your jquery?
$(".volunteerList").value =null;
for(var i=0,vString=i+1+". "+volunteerArray[i]+"\n";i< volunteerArray.length;i++){
$(".volunteerList").value+=vString;
}
Related
I have an ajax call that returns a Serialized JSON string with various keys and values within it, I want to loop through these values and assign each individual key and value to a different label, I already have 8 labels set up. (I am quite new to Javascript so any help or constructive feedback would be greatly appreciated)
Haven't tried much as I am quite new to JavaScript
var obj = response.ret.SearchCriteria;
var resultJSON = obj;
var result = $.parseJSON(resultJSON);
var count = Object.keys(result).length;
for (i = 1; i < count; i++) {
var c = $('#lbl' + [i]);
$.each(result, function(k, v) {
c.text(k + ' is ' + v);
});
};
I have 6 labels and the last item of the JSON array (String) is displayed in each label
I believe your issue is why only last item of JSON array is being displayed in each label.
This is because of c.text(k + ' is ' + v).
Here the existing text content is replaced with every iteration of 'each' loop
Instead, you can consider doing this, which will append existing content as well with $.each loop.
c.text(c.text() + k + ' is ' + v)
OR
Simply
c.append( k + ' is ' + v)
If I am wrong in my assumption, please describe your scenario more, so that we can help you out :)
Thanks for the answers on the previous two questions. I have a new one, and this one is a collapsible panel in jQuery. The concept is, the first key of a JSON object will appear as a button, and the other keys will be treated as regular text like <p> and the like.
I have this function which tests for the first index of an object.
function isFirstIndex(obj){
var key;
for(key in obj){
if(obj[key]===0){
return true;
}
}
return false;
}
I have tried this one:
function generateTree(data, selId){
var cnt = "";
for (var i=0; i<5; i++){
var row = data[i];
$.each(row, function(key,value){
if (isFirstIndex(row)){
cnt += "<button>" + value + "</button><br/>";
} else{
cnt += "<strong>" + key + "</strong> :" + value + "<br/>";
}
});
cnt += "<br/>";
}
$(selId).html(cnt);
}
But eventually found out in debugging that the key in the isFirstIndex function is compared with a string.
Suppose I have a JSON :
{"userId" : 1, "name" : "cool name"}
I want to show the first key of any JSON set as a button, and the following properties will be ordinary text. Please allow me to post a pseudo-code like process.
Loop through all elements of data response
Loop through each key and value of each data element.
If the key is the first occurrence within the data set
display it as a button.
else
display it as ordinary text.
End Inner Loop
End outer loop
What UtsavShah means is that for (key in obj) may iterate keys in obj in any order, JS spec does not enforce any order.
In fact, JS spec does not enforce any order not only for iteration, but also for internal storage: each JS engine implementation (hence depending on browsers) may store your JSON keys in any order, so even though you write your "userId" first, it does not mean at all that the browser will keep it as the first key. For that, you have to use an Array, or use a convention with a specific key.
The way your code is written, it will look for a key named "0" in your object (row). BTW your i iterator is useless in isFirstIndex function.
What you may try to achieve is to test if the value assigned to "userId" key is equal to 0? In that case, you would simply test if (obj["userId"] === 0).
EDIT: (after you have explained that userId is the one to be a button)
If you just want the value in key "userId" to be displayed as a button, you would simply do:
function generateTree(data, selId){
var cnt = "";
for (var i=0; i<5; i++){
var row = data[i];
$.each(row, function (key,value) { // Note that $.each does not necessarily iterates in any specific order either.
if (key === "userId"){
cnt += "<button>" + value + "</button><br/>";
} else{
cnt += "<strong>" + key + "</strong> :" + value + "<br/>";
}
});
cnt += "<br/>";
}
$(selId).html(cnt);
}
EDIT2:
If you want an order, you need an array. If you want ordered keys, you could shape your data like so (of course this must be implemented in both server and client):
[
{"userId": 1},
{"name": "cool name"}
]
If you just need to know which particular key is specific and should be set as a button, make up a convention with your server and have your data specify which is the specific key, e.g.:
{
"userId": 1,
"name": "cool name",
"specificKeyToBeTransformedIntoAButton": "userId"
}
Im stuck.
I have a button which returns information about a event, name, date and so on.
In the script it looks like this:
for(var i = 0; i < result.length ; i++)
{
var item = result[i];
$("#eventList").append("<h3>" + result.eventDate + "</h3>" + "<br>" + result.eventId + "<br>" + result.description + "<br>");
}
This generates a list of events that goes to a div, alla of the events in one div. But i would like every event to be placed in one separate div/box.
Any ideas?
You can create them inside a div and then append all of them at the end to the dom.
var divs = [];
var $div;
results.forEach(function(item){
$div = $('<div></div>');
$div.append("<h3>" + item.eventDate + "</h3>");
$div.append("<br>"+ item.eventId);
$div.append("<br>"+ item.description);
divs.push($div);
});
$("#eventList").append(divs);
You can create your item variable inside the for loop. When ii gets too big, result[ii] will be undefined or false, and the loop will stop. I prefer to use ii to i, because it's easier to find if I want to search for a repeat loop.
Each jQuery operation returns the jQuery object that it was applied to, so you can chain your operations. You can create an empty element, and then set its text in the next operation, to make the code more compact.
for(var ii=0, item; item=result[ii]; ii++) {
$("#eventList")
.append($("<div>")
.append($("<h3>").text(item.eventDate))
.append($("<p>").text(item.eventId))
.append($("<p>").text(item.description))
)
}
jsFiddle
I'm currently in a JavaScript course that is asking me to have the following happen:
User enters names one at a time into a form, then presses Submit
The names are stored into an array and output to a table
As names are entered (and added to the table), a total must update as well--based on the array, not just from counting table elements
My current issue is I'll add one name, then the total shows "1"--when I add a second name, the total displays "11"
This is currently what my JavaScript code looks like:
function displayNamesAndTotal() {
// Your code goes in here.
var userInputName = [];
var totalNamesEntered = [];
var countTotal = 0;
var firstName;
var arrayIndex;
var output;
var outputTotal;
var form;
form = document.getElementById("userFormId");
output = document.getElementById("userEntriesId");
outputTotal = document.getElementById("testId");
//userInputName[0] = form.firstname.value;
userInputName.push(form.firstname.value)
for (arrayIndex = 0; arrayIndex < userInputName.length; arrayIndex++) {
output.innerHTML += "<tr><td>" + userInputName[arrayIndex] + "</td></tr>";
countTotal += userInputName.length;
}
outputTotal.innerHTML += countTotal;
return false;
}
I've spent the past day or so trying to figure out what I'm doing wrong--and it's probably something embarrassingly easy--but I'm at a loss and could use guidance
Any suggestions?
Thanks
It looks like your total is storing a string instead of a number. Try using parseInt(number) to convert the string into a number.
Good grief, from reading the other answers from you guys I think I have it licked
for (arrayIndex = 0; arrayIndex < userInputName.length; arrayIndex++) {
tableData = "<tr><td>" + userInputName[arrayIndex] + "</td></tr>";
totalCount = userInputName.length;
}
output.innerHTML += tableData;
outputTotal.innerHTML = "<h4>Total Number of Strings: " + totalCount + "</h4>";
form.string.select();
return false;
This way the totalCount acted as the array's length when it went through the loop, then outside in the innerHTML statement I could display it and have it constantly update whenever a new string was submitted.
Thank you for all of your feedback
outputTotal.innerHTML is a string, so adding to it would concatenate the strings together. Since outputTotal.innerHTML starts out as null, add 1 to it creates "1". When you add 1 to it again, outputTotal.innterHTML is already "1", so it becomes "11".
Instead of incrementing outputTotal.innerHTML try setting the HTML to it directly.
outputTotal.innerHTML = countTotal;
I am getting the data from the database as key value pairs and trying to populate the values in a list view. While looping I would like to change the value of a data (item.student_class) into 'Your next class is 2' if its value is class1. When I try it as below, it changes all the values in the list.
var buffer="";
$.each(data, function(index, val){
for(var i=0; i < val.length; i++){
var item = val[i];
//If the student's class is class1, change its value as below
if(item.student_class= 'class1'){var studentclass='Your next class is 2';}
buffer+='<li id="' + item.student_id+ '" data-student_class="'+studentclass+'"><b>' + item.student_name+'</b><span class="af-badge" style="background-color:#4a4">'+studentclass+'</span><br/>'+item.join_date+'</li>';
}
$('#student_list').html(buffer); });
Could someone please help me how I can acheive it ?
Fix the conditional to not do an assignment.
You are initializing the variable inside the condition and thus it might be undefined in some cases. Set it to "" first: i.e.
var buffer = "";
$.each(data, function (index, val) {
for (var i = 0; i < val.length; i++) {
var studentclass = "";
var item = val[i];
//If the student's class is class1, change its value as below
if (item.student_class == 'class1') {
studentclass = 'Your next class is 2';
}
buffer += '<li id="' + item.student_id + '" data-student_class="' + studentclass + '"><b>' + item.student_name + '</b><span class="af-badge" style="background-color:#4a4">' + studentclass + '</span><br/>' + item.join_date + '</li>';
}
$('#student_list').html(buffer);
});
you are assigning a value, rather than comparing one , try as follows:
if(item.student_class== 'class1'){var studentclass='Your next class is 2';}
When you are assigning a value, it will work every time, and for that all of them will be changed. (probably you know, but it is common miss :-)
If you have multiple options, you can use the switch statement as follow:
var studentClass;
switch (item.student_class){
case ('class1'):
studentClass='Your next class is 2';
break;
case ('class2'):
studentClass="Your next class is 3';
break;
default:
studentClass= "Whatever should it be if nothing from cases apllies";
}
// Add rest of your code