TechRemarker
TechRemarker

Reputation: 2938

Compare two inputs on submit

The following javascript works by comparing two inputs "name" value for "required_email" and "verify_email" before submitting. The problem is the "names" are actually "required-email" and "verify-email". It appears dashes aren't support in the name's in javascript. Clearly the easiest solution would be to use an underscore or no space but that is not possible because the server side form processing looks for particular "names" that use the dashes.

I can add an ID to each of the two inputs, so all I need to know is how to modify the following javascript to compare #input1 with #input2 (aka use the ID's rather than the name values).

function checkEmail(theForm) {
    if (theForm.required_email.value != theForm.verify_email.value)
    {
        alert('Your emails don\'t match.');
        return false;
    } else {
        return true;
    }
}

PS. I need this done in plain javascript (not jQuery or other frameworks).

Upvotes: 0

Views: 1776

Answers (3)

Ryan
Ryan

Reputation: 5682

If you give them both id's then its simple:

var required = document.getElementById('required_email').value;
var verified = document.getElementById('verify_email').value;
if(required != verified){
  alert('emails do not match');
  return false;
}else{
  return true;
}

Upvotes: 0

sarveshseri
sarveshseri

Reputation: 13985

function checkEmail(theForm) {
    if (document.getElementById("required-email").value != document.getElementById("verify-email").value)
    {
        alert('Your emails don\'t match.');
        return false;
    } else {
        return true;
    }
}

Upvotes: 1

Jesse
Jesse

Reputation: 5084

In this situation you can use the other attribute access syntax:

if (theForm["required-email"].value != theForm["verify-email"].value)

Upvotes: 0

Related Questions