Skip to content
Advertisement

Javascript: Detect checked boxes isn’t working with form with only 1 checkbox. Working with 2 or more

I have the function below. It gets the values from checked boxes and transfer it to a textbox. It is working… but only if the form has 2 or more checkboxes.

<script type="text/javascript">
    function sendValue()
    {
        var all_values = '';
        boxes = document.DataRequest.itens.length
        
            for (i = 0; i < boxes; i++)
            {
                if (document.DataRequest.itens[i].checked)
                {
                    all_values = all_values + document.DataRequest.itens[i].value + ","
        
                }
            }
    
        window.opener.document.getElementById('emailto').value = all_values;
        self.close();
    }
</script>

<form name="DataRequest">
    <input name="itens" type="checkbox" value="name1">
    <input name="itens" type="checkbox" value="name2">
</form>

Am I missing something to make this work with only 1 checkbox?

Advertisement

Answer

When there is one item. it does not return array

  function sendValue()
    {
        var all_values = '';
        boxes = document.DataRequest.itens.length
            if(boxes>1)
            {
            for (i = 0; i < boxes; i++)
            {
                if (document.DataRequest.itens[i].checked)
                {
                    all_values = all_values + document.DataRequest.itens[i].value + ","

                }
            }
            }
           else
             {
              if (document.DataRequest.itens.checked)
                {
                    all_values = document.DataRequest.itens.value 

                }
             }

        window.opener.document.getElementById('emailto').value = all_values;
        self.close();
    }
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement