[英]Comparing the Values of Two HTML Forms using JavaScript
我有兩個具有相同屬性的獨立表單。 是否有一種雄辯的方法可以使用 JS/Jquery 比較它們的等價值?
$('#form1').context.forms[0] === $('#form2').context.forms[0]
似乎有效,但我想知道是否有更好的方法。
我正在使用 spring/thymeleaf 來生成表單的內容。
在您的示例中, context
是整個document
,因為當您不將context
參數傳遞給$(selector, context)
時,這是默認值。 所以你的代碼基本上是這樣做的:
document.forms[0] === document.forms[0] // Always true
如果要比較這些表單中的字段值,可以使用.serialize()
:
$('#form1').serialize() === $('#form2').serialize() // Implies fields are in the same order
演示
$('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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.