简体   繁体   English

如果javascript函数中的条件不起作用

[英]if condition in javascript function not working

I need to compare the values and return the message.But the message returned always. 我需要比较这些值并返回消息。但是消息总是返回。 How can i do it? 我该怎么做?

Javascript: 使用Javascript:

 function Calculation() { var grid = document.getElementById("<%=gvGoodReceived.ClientID%>"); for (var i = 0; i < grid.rows.length - 1; i++) { var txtcurrentrcvamount = $("input[id*=txtrcvQuantity]") var cell = $("#gvGoodReceived").find("tr:eq(0)").find("td:eq(2)").text(); } if (txtcurrentrcvamount > cell) { alert("Receive quantity must be less or equal PO quantity"); return false; } return true; } 

You need to take the value of your input: 您需要获取输入

var txtcurrentrcvamount = $("input[id*=txtrcvQuantity]").val()
//                                                      ^^^^^^

Since you're comparing numbers, and val() and text() return strings, you should convert your values to numbers before doing the comparison: 由于要比较数字,并且val()text()返回字符串,因此在进行比较之前,应将值转换为数字:

if (Number(txtcurrentrcvamount) > Number(cell))

Do note that Number(someStringThatIsNotANumber) will return NaN 请注意, Number(someStringThatIsNotANumber)将返回NaN

Because your scope of a variable (txtcurrentrcvamount) is limited in between for loop, That's why this not working outside the loop scope. 因为变量的范围(txtcurrentrcvamount)在for循环之间受到限制,所以这在循环范围外不起作用。

for more detail, you can view this post... scope of variables 更多的细节,你可以查看这个帖子... 的变量的作用域

For using this variable in if condition you have initialized it before the for loop ... 为了在if条件中使用此变量,您已在for循环之前对其进行了初始化...

EDIT: Try this may this help you either. 编辑:试试这个可能对您有帮助。 I think there some other finding to suppose you have two rows in your grid then which row value you want to check because this always return last row value ... and if there a number value for both of the variable assignment txtcurrentrcvamount ,cell then it should be work perfectly. 我认为还有其他发现,假设您的网格中有两行,那么您要检查哪个行值,因为它总是返回最后一个行值 ...,如果两个赋值变量txtcurrentrcvamount ,cell都存在一个数字值txtcurrentrcvamount ,cell那么它应该可以完美地工作。

function Calculation() {
  var grid = document.getElementById("<%=gvGoodReceived.ClientID%>");
  var txtcurrentrcvamount ;
  var cell;
  for (var i = 0; i < grid.rows.length - 1; i++) {
    txtcurrentrcvamount = $("input[id*=txtrcvQuantity]").val();
    cell = $("#gvGoodReceived").find("tr:eq(0)").find("td:eq(2)").text();

  }
  if (Number(txtcurrentrcvamount) > Number(cell)) {
    alert("Receive quantity must be less or equal PO quantity");
    return false;
  }
  return true;
}

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

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