Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/444.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将输入值作为参数传递给按钮中的JavaScript函数_Javascript_Php_Html_Input - Fatal编程技术网

将输入值作为参数传递给按钮中的JavaScript函数

将输入值作为参数传递给按钮中的JavaScript函数,javascript,php,html,input,Javascript,Php,Html,Input,我有一个字段,您可以在其中插入一个数字,我想将这个数字作为参数传递给调用函数的按钮。我尝试了getElementById,但没有按预期工作 我的代码在php内部调用。我从数据库中获取前两个参数(名称、价格),并希望第三个(数量)参数来自该输入。可能吗 <input type="number" min="0" style ="width:4em" id="quantity" name="quantity" /> <input type="button" value="Add t

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

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

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

必须使用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); " />


我尝试了这个方法,得到了一个错误
uncaughttypeerror:无法读取null的属性“value”
请确保函数AddtoCart是在html之后编写的。确保php实际上正在写入$name和$price变量。etc,etc.@Wr1t3r定义
AddToCart
时并不重要,因为只有单击按钮才能调用它。请编辑您的答案,并解释为什么这样可以解决问题。我无法使它工作。我认为问题在于前两个参数是在php循环(以html加载pproducts)中设置的,我希望在用户交互后获得第三个参数。这就是getElementById不起作用的原因。更好的方法是在“添加到购物车”按钮上添加名称和价格。然后,
AddToCart
可以从按下它的按钮读取数据属性。一个重要的原因是,您不需要将参数编码为JavaScript字符串