McJohnson
McJohnson

Reputation: 313

jQuery val() comparison

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

Answers (3)

Vladislav Karamfilov
Vladislav Karamfilov

Reputation: 471

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().

Upvotes: 2

Rory McCrossan
Rory McCrossan

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');
}

Updated fiddle

Upvotes: 6

Daniel A. White
Daniel A. White

Reputation: 190905

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

Upvotes: 5

Related Questions