Search code examples
javascriptcheckboxinnerhtmlgetelementbyid

Javascript innerhtml of checkbox


Well I have some checkboxes with id='0','1','2','3' etc. So I need to get text of checkboxes. Here is code of checkboxes in PHP.

'<input id="'.$i.'"type="checkbox" name="option1" value="a1" onclick="checkYears()">'.$years[$i].'</input>

So i need to get $years[$i]-value. I'm using this code.

while (bool==false)
    {
        if (document.getElementById(i)!=null)
        {
            if (document.getElementById(i).checked)
            {
                years.push(1);
                yearsValue.push(document.getElementById(i).innerHTML);
                document.getElementById(i).innerText="WORKS";
                console.log(yearsValue[i]);
            }
            else
            {
                years.push(0);
                yearsValue.push(document.getElementById(i)).innerHTML);
                console.log(yearsValue[i]);
            }
        }
        else 
        {
            bool=true;
        }
        i++;
    }

0's and 1's are added ok, but when i'm trying to use innerHTML there is and undefined values in consle.

Any suggestions?


Solution

  • InnerHTML gets the HTML content of an element. i.e. the data between the start tag and the end tag. Inputs are empty elements, they cannot have content (in HTML (as opposed to XHTML) they cannot have an end tag either). Your HTML is invalid and you should use a validator.

    You probably want something like this:

    <label>
        <input type="checkbox">
        <span>Text label</span>
    </label>
    

    Then you could get:

    checkbox.parentNode.innerHTML;
    

    or

    checkbox.parentNode.getElementsByTagName('span')[0].innerHTML