<input type="text" name="a" />
<input type="button" onclick="verfy(document.getElementsByName('a').value)" value="驗證" />
報錯:document.getElementsByName('a').value is not a function 或取值為 undefined。
document.getElementsByName() 返回 NodeList (類數組),無 .value 屬性,需索引取元素再取值。
<input type="text" name="a" id="inputA" />
<input type="button" onclick="verfy(document.getElementById('inputA').value)" value="驗證" />
或保留 name:
onclick="verfy(document.getElementsByName('a')[0].value)"
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>驗證示例</title>
<script>
function verfy(val) {
if (!val.trim()) {
alert("請輸入內容");
return;
}
alert("您輸入:" + val);
}
</script>
</head>
<body>
<input type="text" name="a" id="inputA" placeholder="請輸入" />
<input type="button" onclick="verfy(document.getElementById('inputA').value)" value="驗證" />
</body>
</html>
id 精確定位,避免 name 重複導致索引錯誤。document.querySelector('#inputA').value 或 document.forms[0].a.value。document.getElementById('btn').addEventListener('click', () => {
verfy(document.getElementById('inputA').value);
});