getElementsByName 验证

getElementByName validation

我知道如何使用 getElementById 等方法获取要通过 JavaScript 验证的字段。对于此实例,我需要使用 getElementByName 方法。我在 console.log.

中遇到错误 'Cannot read property 'nodeValue' of null

这是我与 getElementByName 方法一起使用的有效代码

HTML

<button name="button1">Hello</button>
<div class="form-row">    
            <div class="field w100">    
                <label for="primary_phone">Primary phone (digits only) *</label>
                <input type="text" name="primary_phone" id="primary_phone" placeholder="hello"></input>

        </div>
    </div>   
    <div class="form-row">      
        <label for="confirm_phone">Confirm phone (digits only) *</label>
        <input type="text" name="confirm_phone" id="confirm_phone"></input>    
    </div> 
  </div>

JavaScript

var btn1 = document.getElementsByName('button1')[0];
var btn1Text = btn1.firstChild.nodeValue;
console.log(btn1Text);

下面是返回错误的代码。

HTML

<button id="button">Button</button>

JavaScript

function validate() {

    var primaryNo = document.getElementsByName('primary_phone')[0];
    var confirmNo = document.getElementsByName('confirm_phone')[0];
    var primaryValue = primaryNo.firstChild.nodeValue;
    var confirmValue = confirmNo.firstChild.nodeValue;

        if (primaryValue !== confirmValue) {
            alert('Numbers do not match');
        } else {
            alert('congratulations')
        }
};

var btn = document.getElementById('button');
btn.addEventListener('click', validate, false);

有什么想法吗?

看起来您可能有 input 个字段,您正试图获取其值。

在那种情况下,它们没有任何子元素,相反你需要得到它们的 value like

var primaryValue = primaryNo.value;
var confirmValue = confirmNo.value;

结果是什么 var btn1 = document.getElementsByName('button1')[0]; 在控制台中 (console.log(btn1);) ?

注意标签名称:button、button1...可能有语法错误。