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
<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>
var btn1 = document.getElementsByName('button1')[0];
var btn1Text = btn1.firstChild.nodeValue;
console.log(btn1Text);
Below is the code that is returning the error.
<button id="button">Button</button>
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;