问题
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