user3260744 user3260744 - 3 months ago 11
Javascript Question

Javascript Array values appearing twice

Hi I am hoping someone can help me. I have 5 input boxes and I am getting the values from these boxes and placing them into an Array in JavaScript and then sorting these values alphabetically this works perfectly. The issue is that for some reason when the values are put into the array it doubles them and it gives the values twice. Any help would be appreciated. Thanks.

<form>
*Choice A
<input type="text" maxlength="100" name="cha" class="answer" rows="1" cols="10">

*Choice B
<input type="text" maxlength="100" name="chb" class="answer" rows="1" cols="10">

*Choice C
<input type="text" maxlength="100" name="chc" class="answer" rows="1" cols="10" >

*Choice D
<input type="text" maxlength="100" name="chd" class="answer" rows="1" cols="10" >

*Choice E
<input type="text" maxlength="100" name="che" class="answer" rows="1" cols="10" >

<input type = "button" id="myBtn" onclick="myFunction()" value ="Selection Sort in Ascending Order">
<br/>
<div id="showInputValues">
</div>
</form>


Here is the Javascript:

<script language="javascript">
var getBtn = document.getElementById('myBtn');
getBtn.onclick = function() {
getTheData() ;
}

function getTheData() {
var answer = document.getElementsByClassName("answer");
var inputValues = new Array();

for (var i in answer) {
//extract the value of input elements
var singleVal = answer[i].value;
if (singleVal !== "" && singleVal !== undefined) {
inputValues.push(singleVal);
}
}
console.log(inputValues);
inputValues.sort();
//Display sorted values on form
console.log(inputValues);
alert( inputValues);
// set the sorted values :
for (var i=0;i<inputValues.length;i++) {
//extract the value of input elements
console.log(i);
console.log(inputValues[i]);
answer[i].value = inputValues[i];
}
}
</script>

Answer

It's because getElementsByClassName returns an array-like object, not an actual array. If you console.dir(answer) you'll see that, in addition to the numeric keys you would find in an array, the object has one key per named element. for in loops loop over every property on an object, so you're getting your values twice.