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.
<
.val()
returns a string. You should use parseInt
or parseFloat
.
There a two problems with your code:
.val()
not string lengthsFor 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().
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