Reputation: 313
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.
Enter the key:
<input type="text" name="key" size="35" id="q17" autocomplete="off">
<input id="charsLeft" type="text" class="count1" disabled>
<br /><br />
Plaintext:
<input type="text" name="key" size="35" id="q18" autocomplete="off">
<input id="charsLeft2" autocapitalize="off" autocorrect="off" type="text" class="count" disabled>
JavaScript:
$(document).ready(function() {
// Count key
$("#q17").keyup(function() {
$('#charsLeft').val($(this).val().length);
});
// Count plaintext
$("#q18").keyup(function() {
$('#charsLeft2').val($(this).val().length);
});
// Compare key|plaintext
if ($('#charsLeft').val() < $('#charsLeft2').val()) {
alert('Key is shorter than the plaintext');
}
});
I am trying to compare the values of the two input fields (charsLeft
and charsLeft2
). What am I missing here? Here is a fiddle: http://jsfiddle.net/2mgzn4pL/
Upvotes: 2
Views: 1124
Reputation: 471
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()
.
Upvotes: 2
Reputation: 337560
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');
}
Upvotes: 6
Reputation: 190905
.val()
returns a string. You should use parseInt
or parseFloat
.
Upvotes: 5