I'm sorry if the title makes no sense. I am attempting to make a text input add strings to an array, which I then want to turn into a visual list. However, when using innerHTML to put the strings into a div, it prints the entire array rather than only the new string being added. Here is my code:
var nameList = [];
function addToList(frm) {
var list = document.getElementById("list");
if(frm.name.value !== "") {
nameList.push(frm.name.value);
} else {
alert("Not a name.");
};
for(var i=0, len=nameList.length; i<len; i++) {
list.innerHTML += "<div>"+nameList[i]+"</div>";
};
}
You can forgo your entire for loop. Everytime you've pushed a name, just add that name to the innerHTML. There is no need to iterate through your entire list everytime.
var nameList = [];
function addToList(frm) {
var list = document.getElementById("list");
if(frm.name.value !== "") {
nameList.push(frm.name.value);
list.innerHTML += "<div>"+frm.name.value+"</div>";
} else {
alert("Not a name.");
};
}
Note: I'm keeping your array assuming that it's used elsewhere outside of the provided snippet.
You're starting at the 0 array index each time you call the function, so it iterates the entire array every time it's called. If you want to only output the newest value when it's added, forget the loop and output frm.name.value each time the function is called.
If you're merely appending the new item to both the array and the HTML when the function is called, you don't need to loop through all items in the array and append them to the HTML; you can just add "<div"+frm.name.value+"</div>" to the HTML.
You'll only need to loop through all the array elements if there's a chance one of them has changed since the last time the function was called.
On an unrelated note, when you're just appending HTML to an element, you'll see a major performance improvement if you use element.insertAdjacentHTML("beforeend",yourHTML); instead of element.innerHTML += yourHTML;. Check out the jsperf test here to see for yourself!
I think your question is not so clear.
I think what you are trying to do is to have the values that have been input so far in an array and at the same time you want to show them on the screen right?
for(var i=0, len=nameList.length; i<len; i++) {
list.innerHTML += "<div>"+nameList[i]+"</div>";
};
The above code that you are running is not right. += is not valid here as it will add whetever html you have already rendered, which is not right.
list.innerHTML = "<div>"+nameList[i]+"</div>";
If you want to do in this way.
Related
here i want to update demox element with all iteration of jsoDemo,but i only get final element in array.How do i arrange loop so that i update one by one ?
function GETJSON() {
for (var i = 0; i < jsoDemo.length; i++) {
var xxx = jsoDemo[i].name;
console.log(xxx);
}
return document.getElementById("demoX").innerHTML = xxx;
//break;
}
You are changing the innerHTML every time you go through the loop so when it finishes you only get the last one. You can either use document.getElementById("demoX").innerHTML += xxx; or if you want it to cycle through them use setInterval. Also, as the above answer states, put it inside the loop
Well, first, updating the DOM from within a loop is a big-time performance "no no" as successive changes to the DOM cause the user agent to rebuild the DOM each time.
Instead, build up a string in your loop and then set the final value of the string into your DOM element once the loop is done.
Also, .innerHTML is for when you are passing a string that contains HTML to an element's content and that causes that string to be parsed by the HTML parser. If you are not assigning a string that contains HTML, use .textContent instead to avoid that extra work.
Now, to your issue, you are using = when you should be using += to have each new value concatenated onto the last value. And, you don't need to return anything from this function, you only need it to update the element:
function GETJSON() {
var result = "";
for (var i = 0; i < jsoDemo.length; i++) {
result += jsoDemo[i].name;
}
document.getElementById("demoX").textContent = result;
}
I have the following piece of code to generate an select list on the fly. The code works okay when the records retrieved are between 0-300 records. However when I try to work with records over this number, 671 records to be exact, the browsers(IE,FF,Chrome,Opera) hang and it seems the javascript is taking up a lot of resources and the browsers become slow after the select option is finally generated after a 5 minute wait....
I am looking for a way to make this more efficient and prevent such hangups as I will work with records upto 5000
$("#idea_selectrel").on("change",function(){
var attributeid = $("option:selected",this).val();
$.post("/OCSRM/PopulateHTMLTablesServlet.do",{"attributeid":attributeid,"table":'idearelations'},function(data){
if(!$.isEmptyObject(data))
{
$("#idea_selectrelvalue option:not(:first)").remove();
var html='';
var len = data.length;
for(var i=0,len = data.length; i<len; i++ )
{
var relvalue = [data[i].relvalue];
var description = [data[i].description];
html +='<option value="'+relvalue+'">'+relvalue+' - '+description+'</option>';
$("#idea_selectrelvalue").append(html).show();
}
}
else
{
alert('No data found.');
}
},'json');
//alert(attributeid);
});
Your code is building up a long string of HTML containing the options. It's also appending the string over and over again to the <select> element.
Move the .append() to after the loop:
for(var i=0,len = data.length; i<len; i++ )
{
var relvalue = [data[i].relvalue];
var description = [data[i].description];
html +='<option value="'+relvalue+'">'+relvalue+' - '+description+'</option>';
}
$("#idea_selectrelvalue").append(html).show();
Not being able to test the code but from what I can tell you're not clearing the html variable inside the loop, currently, the html will be added recursively for every iteration, and every iteration is updating the DOM, which will get pretty large, fast.
I'm not sure if this is by design, but if it's not, try moving the append outside of the loop.
var html='';
var len = data.length;
for(var i=0,len = data.length; i<len; i++ )
{
var relvalue = [data[i].relvalue];
var description = [data[i].description];
html +='<option value="'+relvalue+'">'+relvalue+' - '+description+'</option>';
}
$("#idea_selectrelvalue").append(html).show();
That is a lot of DOM elements that will be slow to load even if created without JS. Assuming you don't have a way to pre-generate the select on the server and send it down, you could try not appending the value in the loop. You could build out a string of option values and then, after the string is created, set the html of the select to the generated string. The DOM manipulation in the loop could be a culprit at that level. However, it is important to note that large or deeply nested DOM elements can be a performance concern regardless.
I'm new to javascript and simply trying to pull links from a webpage so I'm doing the following:
for(link in document.links) {
console.log(link.getAttribute("href");
}
But if I do this:
document.links.item(0).getAttribute("href")
It returns the link for the first href
What am I doing wrong?
Here is the webpage I'm testing against: http://en.wikipedia.org/wiki/JavaScript_syntax
Just get the elements by tag name and avoid the for in loop.
var links = document.getElementsByTagName('a'),
i;
for(i = 0; i < links.length; i += 1){
console.log(links[i].getAttribute("href"));
}
Example Here
For your example, you would have used:
for(link in document.links) {
console.log(document.links[link].getAttribute("href"));
}
While that technically works, it returns prototype properties in addition to the link elements. This will throw errors since .getAttribute("href") won't work for all the return elements.
You could use the hasOwnProperty() method and check.. but still, i'd avoid the for in loop.
for (link in document.links) {
if (document.links.hasOwnProperty(link)) {
console.log(document.links[link]);
}
}
document.links.item
is an array of items.
document.links.item(0) gets the first item in that array.
document.links.item(1) gets the second item in that array.
To answer your question, what you are doing wrong is that you are not looping the links.item array as you did in your first example.
In your code, you are accessing item 0 and only getting the href from that. For that reason, you will only get one link.
What you probably want to do is get the href for all of the of the links at once
var hrefs = [], i
for (i=0;i<document.links.length;++i) {
hrefs.push(document.links.item(i).getAttribute('href'))
}
Then your hrefs array will contains all the urls
I have a form that I want to only submit post data for value which have changed.
So the way I have been doing this is like this:
function submit_form(){
var hd = [];
// hd is a big array that is defined here
// hd ['some id_number'] = 'some value'
// main function
for (var id_number in hd ){
var x=document.getElementById(id_number).selectedIndex;
var y=document.getElementById(id_number).options;
selector_text = y[x].text;
if (hd[id_number] == selector_text){
$(id_number).remove();
}
}
document.forms["my_form"].submit()
}
So the goal is that if the selector equals what is in the array, then don't POST the data.
To do this I have been doing the remove function. Everything up to the remove function works as expected. However when I look at the post data I still get the selected value for the id_numbers that mach the value in hd.
Is there a better way to remove to prevent it from going to the POST data? The id.parent.removeChild(id) method didn't work either.
The jQuery id selector should begin with a #, but yours appears not to:
$('#' + id_number).remove();
Your for-in loop should be a regular incremental for loop, which is the proper way to iterate an array in JavaScript. for-in loops are typically used for iterating object properties rather than array elements.
for (var i=0; i<hd.length; i++) {
// Access hd[i] in the loop
var x=document.getElementById(hd[i]).selectedIndex;
var y=document.getElementById(hd[i]).options;
selector_text = y[x].text;
if (hd[i] == selector_text){
$('#' + hd[i]).remove();
}
}
Since you aren't really using jQuery here except for that line, instead the plain JS version is:
var removeMe = document.getElementById(hd[i]);
removeMe.parentNode.removeChild(removeMe);
In JS, I'm having trouble working out how to split a string coming from an AJAX call.
This is what I have so far:
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
feedUpdateResponse = xmlhttp.responseText;
/////...split script.../////
}
}
xmlhttp.open("GET","https://myDomain.com/myScript.aspx",true);
xmlhttp.send();
Where you have /////...split script...///// in my script above, I need to add a little function that splits the string returned from my AJAX call.
The string simply contains names of DIVs, like this:
feedUpdateResponse = "div1/div2/div3/div4"
I would like to first split the string by its slashes (/) and run a loop through the different values and do stuff to those elements on my page.
To give an idea of what I need to achieve, I have given this example which is a mix of ASP & JS - it's the only way I can possibly describe it (and show that I've had an attempt) :)
MyArray = Split(feedUpdateResponse,"/")
For Each X In MyArray
documentGetElementById('updateAvailable_'+x).style.visibility="visible";
Next
On my page I have an ASP script that produces jquery carousels, all contained by separate DIVs. The DIVs are named DIV1, DIV2 etc. Inside DIV1, for example, is a text element called updateAvailable_div1 which will alert the user "There are new photos available for this feed, please click the refresh button".
Could somebody please explain to me how I can change my example above to work in JS? Just need to split the string into an array and loop through the split values...
You can use .split() to split a string on a specified character with the results returned as an array. So then it's just a matter of looping through the array:
// given your existing variable
// feedUpdateResponse = "div1/div2/div3/div4" as set in the
// code in the question, add this:
var a = feedUpdateResponse.split("/"),
i;
for (i = 0; i < a.length; i++) {
document.getElementById("updateAvailable_" + a[i]).style.visibility
= "visible";
}
Get your array via string.split("/"). Iterate your array using your method of choice. I prefer Array.forEach():
feedUpdateResponse.split("/").forEach(function (item) {
document.getElementById(item).style.visibility = "visible";
});
See the compatibility notes for using .forEach() in older browsers.
As an alternative:
for(element of feedUpdateResponse.split("/")){
do_your_thing();
}
Using for..in will end up giving you the indices on the array (keys), while for..on will give you the elements of the array (values).
You can also do:
for ([index, element] of Object.entries(feedUpdateResponse.split("/"))) {
do_your_thing();
}
In the event that you need the index.
The disadvantage is it not being compatible with IE, but for personal projects or a quick automation script it usually does me plenty fine.
Try this code:
var a = feedUpdateResponse.split("/");
for (i in a) {
document.getElementById("updateAvailable_" + a[i]).style.visibility
= "visible";
}
var feedUpdateResponse = "div1/div2/div3/div4";
var feedUpdateSplit = feedUpdateResponse.split("/");
for (var x = 0; x < feedUpdateSplit.length; x++) {
document.getElementById("updateAvailable_" + feedUpdateSplit[x]).style.visibility = "visible";
}