...

View Full Version : Adding new elements to a HTML element array



zfs
12-25-2006, 05:48 PM
I have (for example) a HTML elements array that looks like this:


<input type="hidden" name="car[]" value="VW">
<input type="hidden" name="car[]" value="Audi">
<input type="hidden" name="car[]" value="Ferrari">
<input type="hidden" name="car[]" value="Dodge">


What I need to do is to insert a new element into that array, but in the middle - NOT in the end. It means that the array order and indexes are important. The result should look like this:


<input type="hidden" name="car[]" value="VW">
<input type="hidden" name="car[]" value="Audi">
<input type="hidden" name="car[]" value="A BRAND NEW CAR!!!!!">
<input type="hidden" name="car[]" value="Ferrari">
<input type="hidden" name="car[]" value="Dodge">

Mr J
12-26-2006, 12:51 AM
Not too sure about this


<div id="d1">

<input type="text" name="car[]" value="VW">
<input type="text" name="car[]" value="Audi">
<input type="text" name="car[]" value="Ferrari">
<input type="text" name="car[]" value="Dodge">

</div>

<script type="text/javascript">

divEl=document.getElementById("d1")
inputEl=divEl.getElementsByTagName("INPUT")


if(inputEl.length%2==0){
half=(inputEl.length/2)+1
}
else{
half=Math.ceil(inputEl.length/2)
}

newEl=document.createElement("INPUT")
newEl.setAttribute("type","text")
newEl.setAttribute("name","car[]")
newEl.setAttribute("value","A BRAND NEW CAR")

divEl.insertBefore(newEl,divEl.childNodes[half])

</script>

jkd
12-26-2006, 02:04 AM
If you can guarantee sequential structure like that:


var cars = document.getElementsByName("car[]");
var middle = cars[Math.floor(cars.length/2)];
var cloned = middle.cloneNode(true);
cloned.value = "something new";
middle.parentNode.insertBefore(cloned, middle);

Mr J
12-26-2006, 09:57 AM
jkd

That is neat:thumbsup:

So simple, yet so right

I later realised that mine produced different results in IE and Firefox:o

I must look more into this cloning myself

Great stuff jkd

zfs
12-26-2006, 12:35 PM
Thanks jkd! It's almost too good to be true :cool:



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum