简体   繁体   English

jQuery检查输入字段的值,并使用1或更大的值

[英]jQuery check value of input field and use if 1 or greater

I'm trying to write a very simple jQuery function which includes checking for a value of an input field and if that is greater than 0, setting a variable counter as that value. 我正在尝试编写一个非常简单的jQuery函数,其中包括检查输入字段的值,如果该值大于0,则将变量counter设置为该值。 Otherwise use another value. 否则,请使用another值。 However, no matter the value of the field, another is always set and I don't understand. 但是,无论该字段的值如何,总是会设置another值,我不理解。

Jquery jQuery的

  $('.test').click(function(e) {
  var counter = 0; 
  var fieldvalue = $("#fieldID").val();

  if (parseInt(fieldvalue >= 1)) {
    counter = fieldvalue;
  } else {
    counter = 0; // in reality this will be a dynamic value
  }
});

The problem is that counter always returns 0. 问题是counter总是返回0。

you mean fieldvalue in if (parseInt(fieldcounter >= 1) and it has wrong parentheses. 你的意思是fieldvalueif (parseInt(fieldcounter >= 1)它有错误的括号内。

 $('.test').click(function(e) { var counter = 0; // in reality this is a dynamic value var fieldvalue = $("#fieldID").val(); if (parseInt(fieldvalue) >= 1) { counter = fieldvalue; } else { counter = 0; } console.log(counter) }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <input type="text" id="fieldID"> <input type="button" value="fieldID" class="test"> 

The correct variable seems to be fieldvalue and not fieldcounter . 正确的变量似乎是fieldvalue而不是fieldcounter The >= comparison must be done outside the parseInt function. > =比较必须在parseInt函数之外进行。 counter must also receive the result of the parseInt funcion, otherwise it could receive a String. counter还必须接收parseInt函数的结果,否则它可能会接收字符串。

var fieldvalue = parseInt($("#fieldID").val());
if (fieldvalue >= 1) {
    counter = fieldvalue;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM