jQuery val() comparison

前端 未结 3 995
执念已碎
执念已碎 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条回答
  • 2021-01-22 01:16

    .val() returns a string. You should use parseInt or parseFloat.

    0 讨论(0)
  • 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().

    0 讨论(0)
  • 2021-01-22 01:23

    You're comparing strings, not integers. You can use parseInt() to convert them. Try this:

    if (parseInt($('#charsLeft').val(), 10) < parseInt($('#charsLeft2').val(), 10)) {
        alert('Key is shorter than the plaintext');
    }
    

    Updated fiddle

    0 讨论(0)
提交回复
热议问题