jQuery val()比较 [英] jQuery val() comparison

查看:91
本文介绍了jQuery val()比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用jQuery比较两个输入字段的值。但是,它似乎是正确的,但当其中一个值较大时,它不会 alert

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:

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

我试图比较两个输入字段的值( charsLeft charsLeft2 )。我在这里错过了什么?这是一个小提琴: http://jsfiddle.net/2mgzn4pL/

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/

推荐答案

你在比较字符串,而不是整数。您可以使用 parseInt()来转换它们。试试这个:

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

更新小提琴

这篇关于jQuery val()比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆