在 php/javascript 中设置来自数据库的最大输入文本数 [英] Set maximum number input text from database in php/javascript

查看:19
本文介绍了在 php/javascript 中设置来自数据库的最大输入文本数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个输入文本,用于确定购物车中商品的购买金额.每个物品的最大购买量不同,最大购买数(max)是从mysql数据库中获取的.我想如果用户输入的项目数超过最大限制,则出现警告.

So I have an input text that is used to determine the amount of the purchase of item in my shopping cart. Each item has a different maximum amount of purchases, the maximum number of purchases (max) is obtained from the mysql database. I want if user input the number of items exceeds the maximum limit, then a warning appear.

购物图表和金额:

数据库示例:

id_item | item          | brands    | max
- - - - - - - - - - - - - - - - - - - - - - -
1       | Baskom Sedang | Lion Star |2
2       | Pinset Anatomi| Selako    |5
3       | Tromol        | Selako    |7

例如,如果我在Baskom sedang"金额中输入 3(超过最大限制),我希望出现警报.

So for example if i type 3 in the "Baskom sedang" amounts (exceeding max limits), i want alert to appear.

我知道我应该包含一个我尝试过的 javascript/代码,但我对 javascript 一无所知,我不擅长 javascript.谢谢..

I know I'm supposed to include a javascript/code that I try, but I do not have any idea about the javascript, i'm not good with javascript. Thank you..

推荐答案

有3种方法可以解决:

  • 将最大信息传输到前端
  • 检查用户何时提交
  • 异步数据检查,如Jquery ajax

将最大信息传输到前端

只需将您的最大信息放入某个隐藏区域,然后使用 javascript 获取并检查.

Just placed your max info into some hidden area, and use javascript to get and check that.

function check(obj){
  var max = obj.getAttribute("data-max");
  if(parseInt(obj.value) > parseInt(max)){
    alert("Amount out of max!");
  }
}

<input name="amount" value="0" data-max="3" onkeyup="check(this);"/>

但是这种方式不推荐并且应该避免,因为用户可以通过查看源代码来获取您的存储数据.

But this way is not recommended and should be avoided, since users can achieve your storeage data by checking source code.

检查用户何时提交

在服务端查看最大值,导致用户体验不佳.

Check the amount with max value at server-side, which leads to poor user experience.

异步数据检查

这主要是推荐和使用的,它异步获取数据.你可以试试jquery.

This is mostly recommended and used, which get data asynchronously. You can try jquery.

假设你的服务器端语言是php,你可以制作一个文件checkMax.php:

Assuming your server-side lang is php, you can make a file checkMax.php:

<?
  $amount = $_POST["amount"];
  $item_id = $_POST["item_id "];
  /* get your max data from database using item_id, then assign $max
     ...
  */
  echo $amount > $max ? 1 : 0

然后你可以通过jquery ajax查看金额.

Then you can check amount by jquery ajax.

<input name="amount" class="amount" data-id="1" value="0"/>
$(".amount").change(function(){
  var amount = $(this).val();
  var item_id = $(this).attr("data-id");
  $.post("checkMax.php", {"amount": amount, "item_id": item_id}, function(data){
     if(data == "1")alert("Amount out of Max!");
  });
});

这篇关于在 php/javascript 中设置来自数据库的最大输入文本数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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