我需要更多的输入标签,而我的 HTML/JavaScript 组合不起作用

I need more input tags, and my HTML/JavaScript combo isn't working

本文关键字:HTML 我的 JavaScript 不起作用 组合 标签 输入      更新时间:2023-09-26

我的测试站点在 http://grocerylistcalculator.site11.com/grocerycalculator.html# 当然,代码可以在视图源代码中找到。PHP 脚本如下:

<?php
    include 'header.html';
    $prices = $_POST['price'];
    $quantities = $_POST['numbe'];
    $total = 0;
    foreach ( $prices as $key => $p ) {
        $total += $p * $quantities[$key];
    }
    print "The total is ". $total;
    include 'footer.html';
?>

注意:PHP不是我写的,而是在不同的问题上提供的。代码本身有效,但我需要能够添加更多输入部分。JavaScript 在页面上。

所以有这个(编辑以创建div,而不是输入(:

function addInput(divName){
    if (counter == limit)  {
        alert("You have reached the limit of adding " + counter + " inputs");
    }
    else {
        var newdiv = document.createElement('div');
        newdiv.innerHTML = "Price of entry " + (counter + 1) + "<input type='number' name='price[]' step='any'>  <br>Number of said entry: <input type='number' name='numbe[]' step='any'>";
        document.getElementById(divName).appendChild(newdiv);
        counter++;
   }
}

但是您在没有参数的情况下调用它:

<p><a href="#" onClick="addInput()">Add a new input section</a><br/></p>

所以首先解决这个问题。然后你可以担心其余的。

此外,请确保将它们添加到form


更新:在表单中,在提交按钮之前,创建一个空div 并将该 ID 传递给 onlclick 函数,如下所示: onClick="addInput('div_id_here')"