使用javascript或jquery进行价格范围验证

时间:2016-02-01 05:55:01

标签: javascript jquery validation

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>    
<form method="post" action="form.php">

   Price : From
    <input type="text" id="price-from"> 

   To: 
    <input type="text" id="price-to">

    <input type="submit">

</form>    
</body>
</html>

我想验证价格范围..价格必须低于Price To。

3 个答案:

答案 0 :(得分:0)

在提交

上调用此方法
function validatePrices()
{
  var priceFrom = parseFloat( $( "#price-from" ).val() );
  var priceTo = parseFloat( $( "#price-to" ).val() );
  if ( !isNaN( priceFrom )  && !isNaN( priceTo)  )
  {
    if ( priceFrom >= priceTo )//if greater than or equal to then show error alert
    {
       alert( "price from should be less than price to" );
       return false;
    }
  }
  else
  {
       alert( "price from and price to should be valid numbers " );
       return false;
  }
}

答案 1 :(得分:0)

您可能希望为提交按钮指定一个ID。

$(functoin() {
      var fromPrice = $("#price-from").val();
      var toPrice = $("#price-to").val();

      if (fromPrice != "" && toPrice != "") {
        if (parseFloat(toPrice) > parseFloat(fromPrice) {
            $("#frmPrice").submit()
          }


      });
<!DOCTYPE html>
<html>

<head>
  <title>Page Title</title>
</head>

<body>

  <form method="post" action="form.php" id='frmPrice'>
    Price : From
    <input type="text" id="price-from">To:
    <input type="text" id="price-to">
    <input type="submit" id="btnSubmit">
  </form>

</body>

</html>

答案 2 :(得分:0)

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<form method="post" action="form.php" onsubmit="return validate()">
Price : From
<input type="text" id="price-from"> 

To: 
<input type="text" id="price-to">
<input type="submit">
</form>

</body>
<script>
    var validate=function(){
            var from=document.getElementById("price-from").value;
            var to=document.getElementById("price-to").value;
            if(from<to)
                return true;
            alert("from>=to");
            return false;
        }
</script>
</html>