输入字段值不应大于其他字段值

时间:2018-06-01 15:21:55

标签: javascript jquery

我有两个输入字段,一个用于预付款,另一个用于全额付款,这些字段是从数组中的数据库中提取的。

如果onchangekeyup预付款超过全额付款,则不应输入预付款或应等于全额付款。

我正在尝试使用此代码

<input type="text" value="<?php echo $full_payemnt; ?>" id="full_payment_<?php echo $i; ?>">
<input type="text" id="advance_payment_<?php echo $i; ?>" class="advance">
$('.advance').on('change keyup blur', function(e){ 
  var fullPay = $('#full_payment_'+id[1]).val();
  var advancePay = $('#advance_payment_'+id[1]).val();
  console.log( parseInt(advancePay) > parseInt(fullPay))
    if (parseInt(advancePay ) > parseInt(fullPay)) {
       e.preventDefault();     
       $('#advance_payment_'+id[1]).val(fullPay);
    }
});

3 个答案:

答案 0 :(得分:5)

这是一个如何做到这一点的例子。

&#13;
&#13;
var $full = $('[name=full]');
var $adv = $('[name=adv]');

$adv.on('keyup keydown', function(e) {
  var fullPay = parseInt($full.val(), 10);
  var advPay = parseInt($adv.val(), 10); //tell the parser it is base 10

  if (advPay > fullPay &&
    e.keyCode !== 46 // keycode for delete
    &&
    e.keyCode !== 8 // keycode for backspace
  ) {
    e.preventDefault();
    $adv.val('');
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" name="full" />
<input type="number" name="adv" />
&#13;
&#13;
&#13;

答案 1 :(得分:2)

试试这个,我想你想要这个。

$('.advance').on('change keyup blur', function(e){ 
  id_arr = $(this).attr('id');
	id = id_arr.split("_");
  var fullPay = $('#fullPayment_'+id[1]).val();
  var advancePay = $('#advancePayment_'+id[1]).val();
    if ($(this).val() > parseInt(fullPay)) {
       e.preventDefault();     
       $(this).val(fullPay);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
  <input type="text" value="12" id="fullPayment_1">
  <input type="text" id="advancePayment_1" class="advance">
</tr>
<br>
<tr>
  <input type="text" value="19" id="fullPayment_2">
  <input type="text" id="advancePayment_2" class="advance">
</tr>

答案 2 :(得分:1)

Sam Battat's answer进行了一些更改,以便每次输入错误的条目时都会删除输入的数字,而不是清除字段。

var $full = $('[name=full]');
var $adv = $('[name=adv]');

$adv.on('keyup keydown', function(e) {
  var fullPay = parseInt($full.val(), 10);
  var advPay = parseInt($adv.val(), 10); //tell the parser it is base 10

  if (advPay > fullPay &&
    e.keyCode !== 46 // keycode for delete
    &&
    e.keyCode !== 8 // keycode for backspace
  ) {
    e.preventDefault();
    $the_value = $adv.val();
    $the_value = $the_value.substring(0, $the_value.length - 1);
    $adv.val($the_value);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" name="full" />
<input type="number" name="adv" />