Search code examples
javascriptjqueryhtmlspringthymeleaf

Comparing the Values of Two HTML Forms using JavaScript


I have two separate forms that have identical attributes. Is there an eloquent way to compare their values for equivalence using JS/Jquery?

$('#form1').context.forms[0] === $('#form2').context.forms[0] seems to work but I'm wondering if there is a better way.

I am using spring/thymeleaf to generate the contents of the forms.


Solution

  • In your example, context is the entire document, because that's the default value when you don't pass the context argument to $(selector, context). So your code is basically doing this:

    document.forms[0] === document.forms[0] // Always true
    

    If you want to compare the field values in these forms, you can use .serialize():

    $('#form1').serialize() === $('#form2').serialize() // Implies fields are in the same order
    

    Demo

    $('button').click(function() {
      var identical = $('#form1').serialize() === $('#form2').serialize();
      alert(identical ? "Values are identical" : "Values are NOT identical");
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <form id="form1">
      <label>Name</label>
      <input name="name">
      <label>
        <input type="checkbox" name="accepts_tou">
        Do you accept out Terms of use?
      </label>
    </form>
    <form id="form2">
      <label>Name</label>
      <input name="name">
      <label>
        <input type="checkbox" name="accepts_tou">
        Do you accept out Terms of use?
      </label>
    </form>
    
    <button>Compare</button>