I have a javascript that has custom indexes, I created them like so:
var rand = event.timeStamp; //jquery on click event object
freeze_array[rand] = month + ',' + model_name + ',' + activity;
To remove the above element I have this:
freeze_array.splice(rand, 1);
But this does not remove the element as I can see it in my firebug dom object viewer. Here is an example of the array:
My indexes are in the form: 1283519490632 - too long to be an integer that is required by the splice method?
Thanks all for any help
As you mentioned, the index argument must be an integer. Maybe you can use an object that holds indices as follows:
var lastIndex=0; // that shall be global...
var pointer = {};
....
pointer[rand] = lastIndex;
++lastIndex;
Then use it as follows:
freeze_array = freeze_array.splice(pointer[rand], 1);
Yes the index must be an integer. Your value is too large for a integer.
See at w3schools
index: Required. An integer that
specifies at what position to
add/remove elements
Try this:
delete freeze_array[ rand ];
Related
I have an array of arrays in JavaScript that I'm storing some values in, and I'm attempting to find a way to clear the value within that array when the user removes the specified control from the page, however I'm not finding a good way to do this and anything I try doesn't seem to be working.
What is the best method for clearing the value in the array? I'd prefer the value to be null so that it's skipped when I iterate over the array later on.
I've tried to do MyArray[id][subid] = '' but that still is technically a value. I've also tried to do MyArray[id][subid].length = 0 but that doesn't seem to do anything either. Trying to grab the index and splice it from the array returns a -1 and therefore doesn't work either.
var MyArray;
window.onload = function(){
MyArray = new Array();
}
function EditValuesAdd(){
var Input = document.getElementById('Values-Input').value;
var ID = document.getElementById('FID').value;
var ValueID = ControlID(); // generate GUID
if (!MyArray[ID]) MyArray[ID] = new Array();
MyArray[ID][ValueID] = Input;
document.getElementById('Values').innerHTML += '<a href="#" id="FV-' + ValueID + '" onclick="EditValuesRemove(this.id)"/><br id="V-' + ValueID + '"/>';
}
function EditValuesRemove(id)
{
var ID = document.getElementById('FID').value;
document.getElementById(id).remove();
document.getElementById(id.replace('FV-', 'V-')).remove();
MyArray[ID][id.replace('FV-', '')] = '';
}
I've also tried to do an index of and then splice it from the underlying array but the index always returns -1.
var Index = MyArray[ID].indexOf(id.replace('FV-', ''));
MyArray[ID].splice(Index, 1);
Setting the length to zero has no effect either.
MyArray[ID][id.replace('FV-', '')].length = 0;
I would expect that one of the methods above would clear out the value and make it null so that it is skipped later on but all of the methods I've found and tried so far leave some non-null value.
What you need is an object (a Map), not an array (a list).
Here's a basic idea of how to do it :
MyArray = {};
....
if (!MyArray[ID]) MyArray[ID] = {}
MyArray[ID][ValueID] = Input;
...
delete MyArray[ID][id.replace('FV-', '')];
Check here for more information : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
In the end I used an array of objects MyArray = [] and then using splice/findindex to remove it from the array:
function RemoveItem(id)
{
var Index = MyArray.findIndex(a => a.ID == id.replace('FV-', ''));
MyArray.splice(Index, 1);
document.getElementById(id).remove();
document.getElementById('FVB-' + id.replace('FV-', '')).remove();
}
It doesn't solve the actual question asked but I don't know if there really is an answer since I was using arrays in the wrong manner. Hopefully this at least points someone else in the right direction when dealing with arrays and objects.
I need a value of text box for that I am using document.getElementsByName("elemntName") but the problem is the the name itself is dynamic, something like below.
for(temp = 0 ; temp < arracid.length ; temp++){
cell1=mynewrow.insertCell(4);
cell1.innerHTML="<input type='hidden' name='ACID"+index+"' class='tblrows' id='ACID"+index+"' value='"+arracid[temp]+"'>";
index++;
}
When I tried var acidCount = document.getElementsByName('ACID') its not working and I tried
var acidCount = document.getElementsByName('ACID"+index+"') still not working
For every loop the name is changing like ACID1,ACID2 etc.. can anyone help me how to get the value of this text box?
Since you are already assigning an ID to your inputs, it's recommended to use getElementsById which is faster than getElementsByName (and more accurate because the IDs are supposed to be unique, while the names don't have to be). Try this:
var acidCount = document.getElementById("ACID" + index);
If you still want to use getElementsByName, try this:
var acidCount = document.getElementsByName("ACID" + index);
But remember that getElementsByName returns a list of elements, but the list has only one element, because your names are unique. If you want to get that element in the list, you can use it's index like this:
var acidCount = document.getElementsByName("ACID" + index)[0];
Alternatively, if you want to get the list of all your inputs, first remove the index from the name:
cell1.innerHTML="<input type='hidden' name='ACID' class='tblrows' id='ACID"+index+"' value='"+arracid[temp]+"'>";
Then use:
var acidCount = document.getElementsByName("ACID");
Note: all the above return the DOM element(s). If you're only interested in the value, use the value property:
var acidCount = document.getElementById("ACID" + index).value;
or
var acidCount = document.getElementsByName("ACID" + index)[0].value;
(This is a jquery solution, since the question was initially tagged with jQuery)
You can use the selector of input elements with name starting with ^= ACID:
$("input[name^=ACID]").each(function(){
console.log($(this).val());
});
Issue is with single quoutes and double quotes :
var acidCount = document.getElementsByName("ACID"+index)
Since there can be more than one element with same name, so we need to get first element with that name, I have corrected your query check this, it will work.
var acidCount = document.getElementsByName('ACID'+index)[0].value
Try using wildcard * in the selector which will return all matched elements
document.querySelectorAll('[id*=ACID]')
You can try using class name.
$(document).find(".tblrows").each(function(){
console.log($(this).val());
});
Since you are naming your elements 'ACID' + index, you can utilize the querySelector method as follows:
for (var i=0; i < arracid.length; i++) {
var $el = document.querySelector('#ACID' + i));
}
I'm newbie to the Javascript/Jquery world.
I have a div with several links and i want to collect the url's .
Then i want to extract from those href's the last 9 characters (actually i wish to optimize it and collect the digits independently the length at the end of each string).I tried to extract them with the slice() method but it does not work.
In console the error is
Object doesn't support property or method 'slice'
Can i convert the object to a string ? Your help is appreciated !
The code is the following
$(document).ready(function(){
var $posts= $('a.entry_title').each(function(){
$(this).attr('href');
});
var posts1 = $posts[0].slice(-9);
var posts2 = $posts[1].slice(-9);
var posts = ["MyURL"+ posts1,"MyURL"+posts2]
$('#div1').load(posts[0] + " .shadow3");
$('#div2').load(posts[1] + " .shadow3");
});
</script>
You see Object doesn't support because $.each returns a jQuery object.
Use .map() instead because it returns an array on which slice would work
var $posts= $('a.entry_title').map(function(){
return $(this).attr('href');
});
Result would be
["link1", "link2", "link3"....] // just a sample
If you wish to get an array of hrefs with last nine characters of each link you can use map this way
var $posts= $('a.entry_title').map(function(){
return $(this).attr('href').slice(-9); // or you can do your own magic
});
Result would look like this
["k1", "k2", "k3"....] // after slicing the words
Try next one:
var hrefs = []; // list of collected and sliced hrefs.
var $posts= $('a.entry_title').each(function() {
// slice & push each href into list.
hrefs.push($(this).attr('href').slice(-9));
});
console.log('href list:', hrefs); // control result.
var posts = ["MyURL"+ hrefs[0],"MyURL"+hrefs[1]]
I have a string array variable called 'myAttachmentArray[]' which holds different figures like this:
[0] - 50000
[1] - 51010
[2] - 52000
[3] - 50010
And the array size is dependent on an int variable called 'squadNumbers'
What I want to do, is to place all the 'myAttachmentArray[]' into another string variable called 'currentAttachments', but with a ',' in between each array value.
So, currentAttachments would = 50000,51010,52000,50010 ...
The only problem is that the array size is dynamic, so I can't do:
currentAttachments = myAttachmentArray[0]+","+myAttachmentArray[1]...
So I tried a for loop:
for(var i = 0; i <= (squadNumbers - 1); i++){
currentAttachments = currentAttachments + myAttachmentArray[i] + ",";
}
But I still don't get what I want ...Please help
You need to use join
currentAttachments = myAttachmentArray.join(",");
If it's really an array, you can use join:
myAttachmentArray.length = squadNumbers;
var str = myAttachmentArray.join(",");
That makes sure the array length is the value from squadNumbers, and then uses join to join together those entries. Each entry will be turned into a string, then joined using the delimiter you specify.
(But why is the number of entries in squadNumbers rather than just in myAttachmentArray.length in the first place?)
Like this?
currentAttachments = myAttachmentArray.join(",")
For example, I have such HTML:
<input name="someinput[]">
I made a function to clone/remove this input but now I want to assign indexes to name dynamically - when I make an element clones, its new names should be someinput[1], someinput[2] etc. - how to make this?
You could just replace [] with [index] using the attr callback:
var i = 0;
$('button').click(function(){
$('input:first').clone().attr('name',function(a,e){
i++;
return e.replace("[]","["+i+"]");
}).insertAfter($('input:last'));
});
example: http://jsfiddle.net/niklasvh/c9G7c/
Keep the index of the next input in a global variable, and then use that in your cloning function. Is that what you do?
var source = $('#source')
var copy = source.clone().attr('name', 'some[' + index + ']')
$('body').append(copy);