Wern Ancheta
Wern Ancheta

Reputation: 23337

How to make arrays work in javascript?

I'm trying to decrease or increase the value in a textbox using javascript. I made it work, when not using any arrays on it. If you're asking why I need arrays on this one. Its because I'm gonna need to integrate it later on a bigger project which heavily needs array on it. I'm a beginner in javascript, so I don't really know what are the requirements in making this work when making use of arrays.

<html>
<head>
  <script type="text/javascript">
    function blabla(){
        var a= document.x.qty[].value;
        var b=document.x.qty2[].value;
        var pa=parseInt(a);
        var plusqty= pa + 1;
        var txt = plusqty;
        var tbox = document.getElementById('qty');
        if (tbox)
        {
            tbox.value = txt;
        }

    }

    function lastog(){
        var a= document.x.qty.value;
        var b=document.x.qty2.value;
        var pa=parseInt(a);
        var plusqty= pa - 1;
        var txt = plusqty;
        var tbox = document.getElementById('qty');
        if (tbox)
        {
            tbox.value = txt;
        }
    }
  </script>
</head>

<body>
  <form name="x">
    number 1<input type="text" id="qty" name="qty[]" value=""><br/>
    number 2<input type="text" id="qty2" name="qty2" value=""><br/>
    number 3<input type="text" id="qty3" name="qty3" value=""><br/>
    <a href=""><img src="add-icon.png" onmouseover="blabla();"></img></a>
    <a href=""><img src="delete-icon.png" onmouseover="lastog();"></img></a>
  </form>
</body>
</html>

I also tried iterating through it using the usual for loop, but I cant make it work:

function blabla(){
    for (int i=0; i<arr.length; i++){
        var a= document.x.qty[].value;
        var b=document.x.qty2[].value;
        var pa=parseInt(a);
        var plusqty= pa + 1;
        var txt = plusqty;
        var tbox = document.getElementById('qty');
        if (tbox)
        {
            tbox.value = txt;
        }
    }
}

Upvotes: -1

Views: 148

Answers (1)

Nick Craver
Nick Craver

Reputation: 630637

You need to use bracket notation to access a property worth special characters in the name, like this:

var a = document.x["qty[]"].value;
var b = document.x["qty2[]"].value;

Though, if they have IDs, it's much easier to do:

var a = document.getElementById("qty").value;

Or for example looping through all with that name:

var qtyElements = document.getElementsByName("qty[]");
for(var i=0; i<qtyElements.length; i++) {
  alert(qtyElements[i].value);
}

Upvotes: 4

Related Questions