Javascript innerhtml of checkbox

折月煮酒 提交于 2019-11-30 09:45:36

问题


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?


回答1:


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



回答2:


An input element does not have an innerhtml because the element is supposed to be self-closing:

<input type="checkbox" name="checkbox" value="1" />




回答3:


You can't because <input> doesn't have close tag, so it doesn't have innerHTML property:

Must have a start tag and must not have an end tag.

From MDN.

I recomend you to use combination of label and input.




回答4:


Ideally a input element will not have any innerHTML. That means you cannot have an enclosing html content in input element. You can just have value of input element.




回答5:


As pointed out, input elements are self-closing and do not have innerHTML. Best solution if you want to catch the plain text next to the checkbox element would be to use "nextElementSibling" and "innerText".

<input type="checkbox" id="checkbox1"> <span>Text to get...</span>
<button onclick="getText()">Get Text</button>

JavaScript:

function getText() {
     console.log(document.getElementById("checkbox1").nextElementSibling.innerText);
}


来源:https://stackoverflow.com/questions/10143211/javascript-innerhtml-of-checkbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!