0

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?

6 Answers 6

2

You need to set the value in Javascript:

document.getElementById(...).value = startTimeList[0];
Sign up to request clarification or add additional context in comments.

2 Comments

This can't work as there is no id in the input, but that's the general idea. A solution is to add an ID, of course, and that's generally better than just using the name.
you can use document.getElementsByName('yourName')[index_of_element]
1

Use this :

<script>
window.onload = function() {
    document.getElementsByName("startTime1")[0].value = startTimeList[0];
}
</script>

4 Comments

Why this => document.getElementsByName("startTime1")[0].value above?
I'm sorry but I don't get your question. I used "name" because OP didn't give an ID to his input. But I'm sure he'll use all the numerous answer to build the solution he likes...
Oh.Ok. I just did'nt understand your syntax. But, understood it now. Thanks :-)
+1 for answering the question without adding "id" to the code first.
0

You have to set value from javascript. Something like document.getElementById (ID).value = startTimeList[0];

You execute javascript from body oload event.

Comments

0

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.

2 Comments

This can't work as there is no id in the input, but that's the general idea.
Yep! Corrected my post. Thanks.
0

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;

  1. Give your element an ID for example id="ex"
  2. Get the element with JavaScript(of course once the DOM is ready) with var element = document.getElementById('ex')
  3. Change the value with element.value = 'your value';

Comments

0

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('|');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.