简体   繁体   中英

getElementByName validation

I know how to get fields to validate with JavaScript using methods such as getElementById etc. For this instance I need to use the getElementByName method. I have the error 'Cannot read property 'nodeValue' of null in console.log.

Here is code that I used with the getElementByName method which worked

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);

Below is the code that is returning the error.

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);

Any ideas?

Looks like you might be having input fields whose value you are trying to fetch.

In that case, they don't have any child elements, instead you need to get their value like

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

What is the result of var btn1 = document.getElementsByName('button1')[0]; in console (console.log(btn1);) ?

Be careful with tag names: button, button1... maybe you have a syntax mistake.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM