jQuery val() comparison

前端 未结 3 994
执念已碎
执念已碎 2021-01-22 00:21

I am trying to compare the values of two input fields with jQuery. However, it does seem correct but it doesn\'t alert when one of the values is larger.

<         


        
3条回答
  •  -上瘾入骨i
    2021-01-22 01:18

    There a two problems with your code:

    1. You're comparing string values with .val() not string lengths
    2. Your comparison code is executed on page load - which means only when the page has loaded you'll see the result, but on this event the result is false and nothing is being alerted.

    For the first problem you should compare string lengths this way $('#charsLeft').val().length < $('#charsLeft2').val().length.

    For the second problem you should put your comparison code in a button's click event handler function or something in this sort. Another option is to use the focusout event of the second input and attach an event handler with .focusout().

提交回复
热议问题