【问题标题】:Pass input value to a JavaScript function in a button as a parameter将输入值作为参数传递给按钮中的 JavaScript 函数
【发布时间】:2015-03-23 13:11:09
【问题描述】:

我有一个可以插入数字的字段,我想将此数字作为参数传递给调用函数的按钮。我尝试了getElementById,但没有按预期工作。

我的代码在 php.ini 中被调用。我从数据库中获取前 2 个参数(名称、价格),我希望第三个(数量)参数来自该输入。有可能吗?

<input type="number"  min="0" style ="width:4em" id="quantity" name="quantity" />
<input type="button" value="Add to Cart" onclick="AddtoCart(\''.$name.'\',\''.$price.'\',quantity); " />

【问题讨论】:

  • 更好的方法是在添加到购物车按钮上将名称和价格添加为data attributes。然后AddToCart 可以从按下它的按钮中读取数据属性。一个重要的原因是您不会将参数编码为 JavaScript 字符串

标签: javascript php html input


【解决方案1】:

来自 php 的变量必须使用 php 开始和结束标签正确传递给 html:

<input type="number"  min="0" style ="width:4em" id="quantity" name="quantity" />
<input type="button" value="Add to Cart" onclick="AddtoCart('<?php echo $name; ?>', '<?php echo $price; ?>',document.getElementById('quantity').value); " />

【讨论】:

  • 我试过这个,我得到这个错误Uncaught TypeError: Cannot read property 'value' of null
  • 请确保AddtoCart函数写在html之后。确保 php 实际上正在写入 $name 和 $price 变量。等等等等。
  • @Wr1t3r 何时定义 AddToCart 并不重要,因为在您单击按钮之前不会调用它
  • 请编辑您的答案,并解释为什么这样可以解决问题。
  • 我无法让它工作。我认为问题在于前两个参数是在 php 循环中设置的(它在 html 中加载 pproducts),我希望在用户交互后获得第三个参数。这就是为什么 getElementById 不起作用的原因。
猜你喜欢
  • 1970-01-01
  • 2018-04-22
  • 2020-04-26
  • 1970-01-01
  • 1970-01-01
  • 2020-12-23
  • 1970-01-01
  • 2013-01-03
  • 2015-06-09
相关资源
最近更新 更多