How to set certain element values to null in JavaSctipt - javascript

I have some items I am storing in an element that get added at various times like this:
document.getElementById('rout_markers').value = str;
I am not too good with JavaScript, but as I understand it, the values get stored as an array, correct?
What I need to do is to be able to remove all the elements or to be able to remove the last element that was added.
How can I do that?
Thanks!

If you're assigning str to an element then there are no arrays involved here - you'll be overwriting each previously-assigned value with the latest and thereby storing only the latest value.
You could use an array but you'd have to know the location of each item in the array, so if you wanted to assign or nullify a specific element in your array, you'd have to a have a record of where it was - although you could get around that it with a multi-dimensioned array, where the first element at each index is the name of the property, and the second element at each index is that value of the property.
If you want to store multiple properties in a field in order to retrieve them all later, there are two simple ways of doing this.
Consider using either a field for every property.
If you do this then I'd suggest using a naming convention for the fields so that you can more easily assign the property.
Concatenating a string to form a collection of key-value pairs, very much like a query-string.
In the example you gave, this would mean storing something like:
var keyVals = 'route_markers' + '=' + str + '&';
document.getElementById('myHiddenProperties').value = keyVals;
When you want to assign another property to this string you do something like this:
keyVals = document.getElementById('myHiddenProperties').value;
keyVals += 'new_property' + '=' + myNewValue + '&';
document.getElementById('myHiddenProperties').value = keyVals;
In this way, if you want to remove a specific key-value pair, you split the stored value like this
var arrKeyVals = document.getElementById('myHiddenProperties').value.split('&');
You then have an array of key-value pairs.
If you want to retrieve a value from this array, or blank one of the values then loop through this array, splitting each into its key and value, like this:
for (var i = 0; i < arrKeyVals.length; i++) {
var keyVal = arrKeyVals[i].split('=');
var key = keyVal[0];
var val = keyVal[1];
if (key == name_of_key_sought) {
val = ''; //assign an empty string to this property to forget about it
}
}

I am not too good with JavaScript, but as I understand it, the values get stored as an array, correct?
No, the value property of certain HTML elements is just a string value. (And it only exists on certain elements, like input.) Assigning a new value to value will overwrite the previous value, not store it in an array.
What I need to do is to be able to remove all the elements or to be able to remove the last element that was added.
This part of the question sort of goes away because of the answer to the first part, but you can clear the value property by assigning an empty string to it.

If by any chance you mean remove/hide the element itself (the text box) then you can have such code:
document.getElementById('rout_markers').style.display = 'none';
Otherwise the other answers here cover it all nicely.

Related

How to replace the javascript object property name dynamically

I have created a JavaScript object like
var obj={}
var prop = {}
prop.name= "name",
prop.value = "10"
obj[old_name] = prop;
I need to change the old_name to new_name. I have tried
obj[new_name] = obj[old_name];
delete obj[old_name];
And it works but, the object order gets changed.
For example:
{"obj1":{"name:name","value:10"},"obj2":{"name:name","value:10"}}
If I replace obj1 with objone, like this:
obj[objone ] = obj[obj1];
delete obj[obj1 ];
The object order changed to:
{"obj2":{"name:name","value:10"},"objone":{"name:name","value:10"}}]
But I need to change the property name alone and not the order, and I also try string replace but I think it is not the proper way, so please suggest me some ideas.
Objects have no order. Any apparent order you see is unspecified behavior and you cannot rely on it. They didn't when the question was asked, but they do now:
Let keys be a new empty List.
For each own property key P of O that is an integer index, in ascending numeric index order
Add P as the last element of keys.
For each own property key P of O that is a String but is not an integer index, in property creation order
Add P as the last element of keys.
For each own property key P of O that is a Symbol, in property creation order
Add P as the last element of keys.
Return keys.
Your way of renaming the property is the only way of doing it: Creating a new one, then removing the old one. Doing that will change where it appears in the order of the object, because it was created after the previous property.
If you need order, use an array. While theoretically arrays don't have order either (because they're not really arrays), we have the convention that they have order, based on then numeric value of the indexes of the entries: The entry at index 0 is before the entry at index 1 and so on. (And modern JavaScript engines can and do use real arrays where possible.)

How can I store values from one array to another array using 'for' loop

I am trying to create number of arrays like _temp0[],_temp1[],_temp2[] so on and I want to store values of data[] in it.
so value of data[0] goes in array_temp0[] after splitting,
data[1] goes in _temp1[] and so on
to elaborate more-
If value of data[0] is string a,b,c
then array _temp0[] should be
_temp0[0]=a
_temp0[1]=b
_temp0[2]=c
I wrote this function
for(var k=0;k<data.length-1;k++)
{
window['_temp' + k] = new Array();
alert("actual data -- >"+data[k]);
'_temp'+k= data[k].split(',');
alert("data after split -- >"_temp[k]);
}
but it is not working, how do I solve it?
You can do the same using javascript objects. Here is an example of how to do it.
Create an object of name '_temp':
var _temp = {};
When you iterate through 'data' variable then, you can dynamically add attributes to it,say _temp['data0'], _temp['data1'] etc, and every attribute will be an array. For that, you need to write something like:
for(var k=0;k<data.length-1;k++)
{
_temp['data'+k] = data[k].split(',');
}
This will not create the variables identical to what you want. However, this is similar to what you want.
used
window['_temp'+k]= data[k].split(',');
instead of
'_temp'+k= data[k].split(',');
and it worked, thanks to go-oleg

Get ID by key in localStorage

In JS localStorage I can use
localStorage.getItem(key);
to get the value of the entry corresponding to the key in the key variable.
How can I get the entry's ID (instead of value) using the key?
Edit: sorry I must have confused people. What I mean by "key" is the numerical key - which is 0, 1, 2, 3 etc depending on how many items have been saved. Then I want to find out the ID it was stored as, eg foo in the below example, from the numerical key.
localStorage.setItem('foo', 'bar');
LocalStorage is implemented as a key-value pair ( see for instance: https://developers.google.com/web-toolkit/doc/latest/DevGuideHtml5Storage ) - so you don't have an id like an unique auto-incremented id in a database table.
However, you can access the elements using an index - to get the index of a key in localStorage, the only way I can find is to loop through each key until you find the one you are searching for, like this:
var findIndexOfKey = function(searchKey) {
for (var i = 0; i < localStorage.length; i++){
var key = localStorage.key(i);
if(key === searchKey)
return i;
}
return -1;
}
And then, to retrieve the key using the index, you can do:
localStorage.key(myIndex);
And to retrieve the value, you can do this:
localStorage.getItem(localStorage.key(myIndex));
... or this ( which would be equivalent to localStorage.getItem("myKey")):
localStorage.getItem(localStorage.key(findIndexOfKey("myKey")));
when setting the item you should give it's ID as a value and than when you call getItem(key) it should give it's ID as a return ex:
localStorage.setItem('foo', 'bar');
localStorage.getItem('foo'); // it should return the bar
take a look for this examples it may help : http://mathiasbynens.be/notes/localstorage-pattern
The answer:
localStorage.key(key);
Sorry, I realise I've got confused between what's actually called the key, which I called the ID, and it's numerical ID which I called the key...
I don't think it is possible. Can't you just make localStorage.setItem(yourkey,value)? I mean
localStorage.setItem(0,value)
localStorage.setItem(1,value)
This may be useful in loops for example.

Setting the last element of an array to a separate String and then removing said element

I have an array that could have between 1 and 11 elements. I want to remove the last element and make it a new string, then set the rest of the arraylist to a collective string. The following code isn't working...Do I need to include an if else incase the arraylist has only one element? (I know I do, I'm wondering if that would cause the script not to be executed at all)
var finaling = checked[checked.length].toString();
checked.splice(checked[checked.length]);
checked.toString();
Here is how I would do it...
I want to remove the last element...
checked.pop();
...and make it a new string...
checked.push('new string');
// or skip the above `pop()`
checked[checked.length - 1] = 'new string';
...then set the rest of the arraylist to a collective string.
checked = checked + '';
The default toString() of an array will join the elements with a ','. If you want to use a different joining character, use join().
I'm not sure what you're trying to do but this should do it:
var lastElementInArray = checked.splice(checked.length-1)[0].toString();
var stringOfChecked = checked.toString();
Or if you want to remove the last element of an array and return a string representing the new array:
checked.splice(checked.length-1, 1);
var finaling = checked.toString();
Something to note: array.splice() returns an array of elements; if you only have one element in it and you want that actual element, you'll want to use array.splice(...)[0].

json jquery filter javascript array

I have a json object array. I want to search the array and for each object, create a list of 'services' that is a comma-seperated list of all the keys which have a value of "yes".
The list of json objects with the services list is then displayed in html using jquery's each.
Its a large json file so I want to do it as efficiently as possible.
I already have the object's properties being accessed through jQuery's each (ie, obj.name)
-- so I think it should be possible to filter the services listed for each object using
jQuery's filter, and then display the key if the value is yes.
But it seems like a more efficient option would probably be to create a new javascript array, join the services with a value of yes and then add that variable to the html being
appended.
Im not sure which would be faster and so far havent been very successful at either... so any advice and examples would be very helpful.
Here's what the json array looks like:
[
{"name":"name1",
"service1":"y",
"service2":"y",
"service3":"n",
},
{"name":"name2",
"service1":"n",
"service2":"y",
"service3":"n",
},
];
If you just want to filter the array then use grep.
grep - Finds the elements of an array which satisfy a filter function. The original array is not affected.
http://api.jquery.com/jQuery.grep/
First off, delete trailing commas. Internet Explorer gets really, really confused by them. Anyway, I assume you don't want to "search" the array when you say "for each value"; you want to iterate through the array and parse it into a more usable list. The first method I'd suggest is just passing what you want as the array you desire, but if that's not an option, what you're looking for is some variant of this, which should be fairly efficient (jsFiddle example):
var json = [
{"name":"name1", "service1":"y", "service2":"y", "service3":"n"},
{"name":"name2", "service1":"n", "service2":"y", "service3":"n"}
];
var parsed = {};
for (var i = 0, iLen = json.length; i < iLen; i++) {
// Assuming all we need are the name and a list
var name;
var list = [];
for (var key in json[i]) {
var value = json[i][key];
// We need to hold on to the name or any services with value "y"
if (key === "name") {
name = value;
} else if (value === "y") {
list.push(key);
}
}
// Add them to the parsed array however you'd like
// I'm assuming you want to just list them in plain text
parsed[name] = list.join(", ");
}
// List them on the web page
for (var key in parsed) {
document.write(key + ": " + parsed[key] + "<br>");
}
That way you wind up with a display to the visitor of the services available and still keep an array around for further use if necessary.
jQuery.inArray() Search for a specified value within an array and return its index (or -1 if not found).
http://api.jquery.com/jQuery.inArray/
Or
http://api.jquery.com/jQuery.each/

Categories

Resources