Mounting array with checkbox

Asked

Viewed 1,240 times

1

I would like to mature the idea below to send a variable in Javascript to Asp and with the choices in array, I’m only managing 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
%>

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 this does not require Javascript. Just use the form:

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

(attention to duplicate Ids in HTML)

Anyway the real problem in Javascript you have is what you’re doing document.location.href within the for and this code opens the page with the given link, without ending the loop.

Fixing 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.