How to deep copy string in javascript? - javascript

I'm new to JavaScript and have a basic question. I have 2 text fields on a server-generated page, and I want to copy the text value of field 1 to field 2, and then set field 1's value to an empty string. The problem is since JavaScript is doing a shallow copy, field 2's value is set to an empty string as well.
Here is the code:
var eleTxtInit = document.getElementById("InputText0");
if (eleTxtInit == null) {
eleTxtInit = document.getElementsByName("InputText0");
}
var eleTxtControl = document.getElementById("InputText1");
if (eleTxtControl == null) {
eleTxtControl = document.getElementsByName("InputText1");
}
eleTxtControl.value = eleTxtInit.value;
eleTxtInit.value = "";
The result of the above code is that InputText1 value becomes "" as well :( ..
What's the solution here ?

I think your problem is: eleTxtControl = document.getElementsByName("InputText1");. getElementsByName returns a Nodelist, so you should use
eleTxtInit = document.getElementsByName("InputText0")[0];
//and ofcourse
eleTxtControl = document.getElementsByName("InputText1")[0];
See jsfiddle

eleTxtInit = document.getElementsByName("InputText0");
triggering will result in the subsequent code failure, since document.getElementsByName returns an HTMLCollection, not an Element. Ditto for eleTxtControl.

Related

JavaScript Clearing Array Value

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.

Using indexof value to return a value in a second array using Javascript

I'm trying to take a user's prompt to find the index position of an item in an array
and retrieve the value of that same index position in a second array.
var arrayStars = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"];
var arrayConstellations = ["Ursa Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Minor", "Leo"];
function starSearch(param) {
var matchingConstellation = arrayConstellations[arrayStars.indexOf("param")];
return matchingConstellation;
}
var userInput = prompt("Enter a star name");
starSearch(userInput);
When I enter text in the prompt there is no response.
I've tried logging to the console after every line to see what output there is if any and it all seems to work but for some reason it doesn't give the intended result.
I've even replaced one of the array values into the line
var matchingConstellation = arrayConstellations[arrayStars.indexOf("Vega")];
And that returns the proper index item from the second array. It just doesn't seem to display a result when everything is together.
remove the quotes
arrayStars.indexOf("param")
to
arrayStars.indexOf(param)
you're searching for the string literal param, not whatever the variable param contains
FIDDLE

Show javascript array value in input type hidden

I have a question regarding Javascript array.
I have the following javascript array:
var startTimeList= new Array();
I've put some values in it. Now I have the following input (hidden type):
<input type="hidden" value"startTimeList[0]" name="startTime1" />
Hoewever, this is obviously not correct because the javascript array is not recognized in the input hidden type. So I cant even get one value.
Does anyone know how I can get a value in the input type from a javascript array?
You need to set the value in Javascript:
document.getElementById(...).value = startTimeList[0];
Use this :
<script>
window.onload = function() {
document.getElementsByName("startTime1")[0].value = startTimeList[0];
}
</script>
You have to set value from javascript.
Something like document.getElementById (ID).value = startTimeList[0];
You execute javascript from body oload event.
You need to set the value through JavaScript itself so.
document.getElementById("startTime1").value = startTimeList[0];
Or JQuery
$("#startTime1").val(startTimeList[0]);
Assign "startTime1" as the id above.
You can find your element by name with:
document.getElementsByName(name)[index].value = 'new value';
OR
You should identify your element and then change the value;
Give your element an ID for example id="ex"
Get the element with JavaScript(of course once the DOM is ready) with var element = document.getElementById('ex')
Change the value with element.value = 'your value';
You'd need to split the array into a delimited string and then assign that string to the value of the hidden input.
Then, on postback or similar events you'd want to parse the value back into an array for use in JavaScript:
var startTimeList = [1,2,3,4,5];
var splitList = '';
for(var i = 0; i < startTimeList.length; i++)
{
splitList += startTimeList[i] + '|';
}
and back again:
var splitList = '2|4|6|8|';
var startTimeList = splitList.split('|');

Global var in JavaScript

This is annoying me.
I'm setting an array in beginning of the doc:
var idPartner;
var myar = new Array();
myar[0] = "http://example.com/"+idPartner;
And I'm getting a number over the address, which is the id of partner. Great. But I'm trying to set it without success:
$.address.change(function(event) {
idPartner = 3;
alert(idPartner);
}
Ok. The alert is giving me the right number, but isn't setting it.
What's wrong?
Changing the value of the variable does not re-set the values within the array. That is just something javascript can't do automatically. You would have to re-generate the array for it to have the new id. Could you add the id to the value where you use the array instead of pre-setting the values in the array containing the id?
Edit: For example, you would do:
var myArray = [];
var myId = 0;
myArray[0] = "http://foo.com/id/";
and when you need to use a value from the array, you would do this:
var theVal = myArray[0] + myId;
Try this:
var myvar = ["http://site.com/"];
$.address.change(function(event) {
myvar[1] = 3;
}
then use myvar.join () where you need the full url.
The problem here is that at the line
myar[0] = "http://site.com/"+idPartner;
..you perform a string concatenation, meaning you copy the resulting string into the array at index position 0.
Hence, when later setting idPartnerit won't have any effect on the previously copied string. To avoid such effect you can either always construct the string again when the idPartnervariable updates or you create an object and you evaluate it when you need it like...
var MyObject = function(){
this.idPartner = 0; //default value
};
MyObject.prototype.getUrl = function(){
return "http://site.com/" + this.idPartner;
};
In this way you could use it like
var myGlblUrlObj = new MyObject();
$.address.change(function(event){
myGlblUrlObj.idPartner = ... /setting it here
});
at some later point you can then always get the correct url using
myGlblUrlObj.getUrl();
Now obviously it depends on the complexity of your situation. Maybe the suggested array solution might work as well, although I prefer having it encapsulated somewhere in an object for better reusability.
myar[0] = "http://site.com/" + idPartner;
After this line, myar[0] = "http://site.com/undefined" and it has nothing to do with the variable idPartner no more.
So, after that changing the value of idPartner will affect the value of myar[0].
You need to change the value of myar[0] itself.

How can I assign null value to an array element?

I am facing too small problem, could you give me idea how to solve that.
for(var j=cArray.length-1;j>=0;j--)
{
if(cArray[j]=='.') {
cArray[j]='';
break;
}
else{
cArray[j]='';
}
}
I wrote this for loop in javascript.NULL value is not assigning to array element.
At last i am getting what is the content in cArray[j] only.I can't able to change that value.My declaration is correct or not?
What are you trying to accomplish?
What the code does in this form is that it makes all elements in an array '' (empty) that are after the last '.' element.
If you just want to truncate the array you could do somethink like this:
var jsArray = ['H','e','l','l','o','.','w','o','r','l','d'];
jsArray.length = 5;
alert(jsArray.length); // returns 5
Your code is right. Maybe it is empty? See my demo and observe as it works =)
To truncate the array at the first .:
for(var j=cArray.length-1;j>=0;j--)
{
if(cArray[j]=='.') {
cArray.length = j;
break;
}
}
Or, if the array is really just a string:
var myString = "1.1.1";
var result = myString.split(".");
var firstPart = result[0];
firstPart now contains 1.

Categories