Mounting array with checkbox

1

I would like to mature the idea below of sending a JavaScript variable to asp and with the choices in array , I am only able to send a choice at the moment:

<!DOCTYPE html>
<html>
<head>
<script>
function getElements()
{
var choices = [];
var els = document.getElementsByName('vehicle');
for (var i=0;i<els.length;i++){
  if ( els[i].checked ) {
    choices.push(els[i].value);
    var resultado = choices[i];
    //alert(resultado);
    document.location.href = 'GetElementByName.asp?resultado=' + resultado;
  }
}

}
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<input type="checkbox" name="vehicle" id="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" id="vehicle" value="Car">I have a car<br>

<input type="button" onclick="getElements()" value="How many elements named ?">
</form>
</body>
</html>
<%
pega_resultado = request.queryString("resultado")
Response.Write ">" & pega_resultado
%>
    
asked by anonymous 27.10.2014 / 22:03

1 answer

1

When you have multiple inputs with the same name then you need to join [] to be treated as an array. That is:

name="vehicle[]"

And for this you do not need JavaScript. Just use form :

<form id="form1" name="form1" method="get" action="GetElementByName.asp">

(attention to duplicate IDs in HTML)

Anyway, the real problem with Javascript you have is that you are doing document.location.href within for and that code causes the page to open with the indicated link, without ending the loop.

Correcting the code could be for example:

function getElements() {
    var choices = [];
    var els = document.getElementsByName('vehicle');
    for (var i = 0; i < els.length; i++) {
        if (els[i].checked) choices.push(els[i].value);
    }
    var resultado = choices.join('_');
    alert(resultado);
    document.location.href = 'GetElementByName.asp?resultado=' + resultado;
}
<form id="form1" name="form1" method="post" action="">
    <input type="checkbox" name="vehicle" id="vehicle" value="Bike">I have a bike
    <br>
    <input type="checkbox" name="vehicle" id="vehicle" value="Car">I have a car
    <br>
    <input type="button" onclick="getElements()" value="How many elements named ?">
</form>
    
27.10.2014 / 22:08