javascript 在表单上添加更多字段并插入到 mysql 数据库中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5466256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:17:57  来源:igfitidea点击:

add more fields on form and insert into mysql database

phpjavascriptmysql

提问by Behind the screen

I have a form and I want to give an add more item link to add three textboxes.User can add upto 7 times. that means user can input 7 items at one time.

我有一个表单,我想提供一个添加更多项目链接来添加三个文本框。用户最多可以添加 7 次。这意味着用户可以一次输入 7 个项目。

the second one is I want to insert these 7 items into mysql tables in separate rows. How can I do it.

第二个是我想将这 7 个项目插入到 mysql 表中的单独行中。我该怎么做。

<form name="frmaddservice" action="" method="post" class="jNice" onsubmit="return checkaddservice();">

    <p><label>Customer Name:</label><input name="txtcustname" type="text" class="text-long" /></p>
    <p><label>Customer Phone:</label><input name="txtcustphone" type="text" class="text-long" /></p>        
    <p><label>Customer Email:</label><input name="txtcustemail" type="text" class="text-long" /></p>
    <div id="fieldset">
    <p><label>Item Type:</label>
        <select name="seltype">
        <option>Select Type</option>
        <?php
            while($rowitem = mysql_fetch_assoc($seltype))
            {
        ?>
            <option><?php echo $rowitem['item_name']; ?></option>
        <?php
            }
        ?>
        </select>
    </p>
    <p><label>Item Brand</label><input name="txtitembrand" type="text" class="text-long"></textarea></p>        
    <p><label>Item Quantity:</label><input name="txtqty" type="text" class="text-long" /></p>        
    <p><label>Item Description</label><textarea name="txtdesc"></textarea></p>
    <p><label>Item Warranty Date:</label><input name="txtdate" type="text" class="text-long" /> 
    <script language="JavaScript">
        new tcal ({
        // form name
        'formname': 'frmaddservice',
        // input name   
        'controlname': 'txtdate'
        });
    </script>
    </p>

    <input type="submit" value="Add Service"/>
    </div>

</form>

I have uploaded the file here, please take a look.

我已经把文件上传到这里了,请看一下。

Validation code

验证码

<SCRIPT TYPE="TEXT/JAVASCRIPT">function IsNumeric(strString)
{
    var strValidChars = "0123456789";
    var strChar;
    var blnResult = true;
    if (strString.length == 0) return false;
    for (i = 0; i < strString.length && blnResult == true; i++)
    {
        strChar = strString.charAt(i);
        if (strValidChars.indexOf(strChar) == -1)
        {
            blnResult = false;
        }
    }
        return blnResult;
}function checkaddservice(){
with (window.document)
{
    if(frmaddservice.txtcustname.value == "")
    {
        alert("Please enter Customer's Name.");
        frmaddservice.txtcustname.focus();
        return false;
    }
    if(frmaddservice.txtcustphone.value == "")
    {
        alert("Please enter Customer's phone.");
        frmaddservice.txtcustphone.focus();
        return false;
    }
    if(IsNumeric(frmaddservice.txtcustphone.value) == "false")
    {
        alert("Please enter Valid phone.");
        frmaddservice.txtcustphone.focus();
        return false;
    }
    for(var i=0; i<7; i++)
    {
        if(frmaddservice.elements["seltype" + i].value == "Select Type")
        {
            alert("Please Select Item Type!");
            return false;
        }
        if(frmaddservice.elements["txtqty" + i].value == "")
        {
            alert("Please Enter Item Quantity!");
            return false;
        }
        var qty = frmaddservice.elements["txtqty" + i].value;
        if(IsNumeric(qty) == "false")
        {
            alert("Please Enter Valid Quantity!");
            frmaddservice.elements["txtqty" + i].focus();
            return false;
        }
    }
}}</SCRIPT>

回答by alex

  • Add []to the end of your nameattributes.
  • Clone them on clickof your button.
  • Check to make sure there are less than 7 when you proceed.
  • 添加[]name属性的末尾。
  • 将它们克隆到click您的按钮上。
  • 继续时检查以确保少于 7 个。

回答by Robot Woods

do you have to use php? if you use javascript you can add the fields without refreshing the page.

你必须使用php吗?如果您使用 javascript,您可以在不刷新页面的情况下添加字段。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js"></script>
<script type="text/javascript" charset="utf-8">
    $(function(){

    $(".datepicker").live('click', function() {
        $(this).datepicker({showOn:'focus'}).focus();
    });
    });
    </script>
<script type="text/javascript">
var num=0;
function addField(){
    num++;
    if(num>7){num--;}
    makefields();
}
function rmField(){
    num--;
    if(num<0){num++;}
    makefields();
}

function makefields(){
var fields="";
for(var o=0;o<=num;o++){
fields+="<p><label>Item Type:</label><select name=\"seltype"+o+"\"><option>Select Type</option>";
<?php $seltype = mysql_query("select * from tblitemtype"); while($rowitem = mysql_fetch_assoc($seltype)){ echo "fields+=\"<option>".$rowitem['item_name']."</option>\";"; } ?>
fields+="</select></p>";
fields+="<p><label>Item Brand</label><input name=\"txtitembrand"+o+"\" type=\"text\" class=\"text-long\"></textarea></p>";
fields+="<p><label>Item Quantity:</label><input name=\"txtqty"+o+"\" type=\"text\" class=\"text-long\" /></p>";
fields+="<p><label>Item Description</label><textarea name=\"txtdesc"+o+"\"></textarea></p>";
fields+="<p><label>Item Warranty Date:</label><input name=\"txtdate"+o+"\" type=\"text\" class=\"datepicker\">";
}
fields+="<br/><input type=\"hidden\" name=\"num\" value=\""+o+"\"/>";
if(num!=6){fields+="<button type=\"button\" onclick=\"addField()\">Add</button>";}
if(num>0){fields+="<button type=\"button\" onclick=\"rmField()\">Remove</button>";}
fields+="<input type=\"submit\" value=\"Add Service\"/></form>";
    document.getElementById("fields").innerHTML=fields;
}
</script>
<script language="JavaScript" src="calendar_us.js"></script>

</head>

<body>
<form name="frmaddservice" action="" method="post" class="jNice" onsubmit="return checkaddservice();">
<fieldset>
    <p><label>Customer Name:</label><input name="txtcustname" type="text" class="text-long" /></p>
    <p><label>Customer Phone:</label><input name="txtcustphone" type="text" class="text-long" /></p>        
    <p><label>Customer Email:</label><input name="txtcustemail" type="text" class="text-long" /></p>
    <div id="fields">
    <p><label>Item Type:</label>
        <select name="seltype0">
        <option>Select Type</option>
        <?php $seltype = mysql_query("select * from tblitemtype");
            while($rowitem = mysql_fetch_assoc($seltype))
            {
        ?>
            <option><?php echo $rowitem['item_name']; ?></option>
        <?php
            }
        ?>
        </select>
    </p>
    <p><label>Item Brand</label><input name="txtitembrand0" type="text" class="text-long"></textarea></p>       
    <p><label>Item Quantity:</label><input name="txtqty0" type="text" class="text-long" /></p>        
    <p><label>Item Description</label><textarea name="txtdesc0"></textarea></p>
    <p><label>Item Warranty Date:</label><input name="txtdate0" type="text" class="datepicker"/> 
    </p>
    <input type="hidden" name="num" value="1"/><a href="#" onclick="addField()">Add</a>
    <input type="submit" value="Add Service"/>
    </div>
</fieldset>
</form>


</body>
</html>

and then you'll need to modify this script to accomodate all of the fields and send data to the different tables you have:

然后您需要修改此脚本以容纳所有字段并将数据发送到您拥有的不同表:

<?php
//your connection data
$sets=mysql_real_escape_string($_REQUEST["num"]);
for($loop=0;$loop<$sets;$loop++){
    $b="txtitembrand".$loop;
    $q="txtqty".$loop;
    $d="txtdesc".$loop;
        $brand=mysql_real_escape_string($_REQUEST[$b]);
        $quantity=mysql_real_escape_string($_REQUEST[$q]);
        $description=mysql_real_escape_string($_REQUEST[$d]);
    $store="INSERT INTO tablename (itembrand,quantity,desc) VALUES ('$brand',$quantity,'$description')";
    $go=mysql_query($store);
    }
?> 

回答by Aidan Brumsickle

First of all, your HTML looks a bit funny... I would just modify it slightly:

首先,你的 HTML 看起来有点滑稽......我只是稍微修改一下:

<fieldset>
  <label for='brand'>Item Brand</label><br>
  <input id='brand' name="txtitembrand" type="text" class="text-long"><br>   
  <label for='quantity'>Item Quantity</label><br>
  <input id='quantity' name="txtqty" type="text" class="text-long"><br>      
  <label for='desc'>Item Description</label><br>
  <textarea id='desc' name="txtdesc"></textarea><br>
  <input type="submit" value="Add Service"/>
</fieldset>

Then for the link, you could have something like,

然后对于链接,你可以有类似的东西,

<a href='/mypage.php?action=addrows&numrows=7'>Add more rows!</a>

which would be generated by php code like:

这将由 php 代码生成,例如:

echo '<a href="/mypage.php?action=addrows&numrows=' . $_SESSION['numrows'] . '>Add more rows!</a>';

where you keep track of numrows in a session variable. Then adding rows will look something like this:

您可以在其中跟踪会话变量中的 numrows。然后添加行看起来像这样:

if (isset($_GET['action']) && $_GET['action'] == 'addrows') {
  if (isset($_GET['numrows'])) {
    $numrows = 0 + $_GET['numrows'] // add zero to cast to int
    if ($numrows > 0 && $numrows <= 7) {
      $_SESSION['numrows'] = $numrows;
    }
  }
}

Afterwards you can use $_SESSION['numrows'] to render your HTML:

之后,您可以使用 $_SESSION['numrows'] 来呈现您的 HTML:

for ($i = 0; $i < $_SESSION['numrows']; $i++): ?>
 <fieldset>
  ...
   <input ... name='txtqty<?php echo $i ?>'
  ...
 </fieldset>
 <?php endfor; ?>

which results in field names txtqty1, txtqty2, txtqty3, etc up to 7. Then when you're processing the form, just check for existence of each field.

这导致字段名称 txtqty1、txtqty2、txtqty3 等最多 7 个。然后在处理表单时,只需检查每个字段是否存在。

Alternatively, you can implement this behavior in JavaScript, as Robot Woods suggests above.

或者,您可以在 JavaScript 中实现此行为,正如 Robot Woods 上面建议的那样。

As for your SQL, you can insert multiple rows like this:

至于您的 SQL,您可以像这样插入多行:

INSERT INTO tablename (col1, col2, col3...)
VALUES (row1col1, row1col2, row1col3...) (row2col1...)