newtphp
newtphp

Reputation: 255

plain javascript - get the value of a checked checkbox

var vettore = document.getElementById(id_form).elements;


for (var i = 0; i < vettore.length; i++)
   {
    if (vettore[i].checked)
            {
            contatore++;

            valore_corrente = document.getElementById.elements[i].value;

            stringaFileSelezionati+= valore_corrente;

            stringaFileSelezionati+= '?';
            }
   }

  if (contatore == 0) 
{
alert('Error!!! No file selected!');
return false;
}
 else 
{
    alert(stringaFileSelezionati);

}

The error is in the line:

valore_corrente = document.getElementById.elements[i].value;

how can i get that value?

EDITED: Maybe the error is in the checkboxes creation since I got undefined:

                                    cell1.innerHTML = '<input type="checkbox" name="' + 'checkbox'+" value=" + vettore_nomi_file[i] + '" id="' +i+ '" />'+vettore_nomi_file[i];

Upvotes: 0

Views: 2119

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

You retrieve .value from the same object you retrieved .checked from:

valore_corrente = vettore[i].value;

The object is an HTMLInputElement instance. The value of the checkbox is reflected in the value property, just like whether it's checked is reflected in the checked property.

Here's a complete, working example: Live Copy | Source

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Example</title>
</head>
<body>
  <form id="theform">
    <label><input type="checkbox" value="1" checked>Uno</label>
    <br><label><input type="checkbox" value="2" checked>Due</label>
    <br><label><input type="checkbox" value="3">Tre</label>
    <br><input type="button" id="thebutton" value="Click">
  </form>
  <script>
    document.getElementById("thebutton").onclick = function() {
      var id_form = "theform";
      var vettore = document.getElementById(id_form).elements;

      var contatore = 0;
      var valore_corrente;
      var stringaFileSelezionati = "";

      for (var i = 0; i < vettore.length; i++)
      {
        if (vettore[i].checked)
        {
          contatore++;

          valore_corrente = vettore[i].value;

          stringaFileSelezionati+= valore_corrente;

          stringaFileSelezionati+= '?';
        }
      }

      if (contatore == 0) 
      {
        alert('Error!!! No file selected!');
        return false;
      }
      else 
      {
        alert(stringaFileSelezionati);

      }

    };
  </script>
</body>
</html>

Upvotes: 2

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

I believe this should work:

valore_corrente = vettore[i].value;

Upvotes: 1

Related Questions