-1

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.

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

<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>
Bobby
  • 11,419
  • 5
  • 44
  • 69
Behind the screen
  • 71
  • 1
  • 5
  • 16

3 Answers3

0
  • Add [] to the end of your name attributes.
  • Clone them on click of your button.
  • Check to make sure there are less than 7 when you proceed.
alex
  • 479,566
  • 201
  • 878
  • 984
0

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

<!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);
    }
?> 
Robot Woods
  • 5,677
  • 2
  • 21
  • 30
  • php script sends me 3 error Undefined index: txtitembrand1 in C:\wamp\www\KC\test1.php on line 9 – Behind the screen Mar 29 '11 at 06:27
  • hi Robot Woods, there is some problem, I want to show 1 fieldset when page loads. then if user wants to add more fields he can add. – Behind the screen Mar 29 '11 at 10:11
  • I made the change, but before you just overwrite the old version, look at what I did so that you get understand how you can continue to make changes as needed. (and accept the answer if you feel the question has been resolved) – Robot Woods Mar 29 '11 at 13:48
  • I made the change in my code. I only want that user can add only innter fields of fieldset id. I don't want to add customer information's fields and also want to insert these in 2 tables. – Behind the screen Mar 29 '11 at 19:37
  • when I go with your code there is an error unterminated string literal in fields+="

    ..... please help me out

    – Behind the screen Mar 29 '11 at 19:42
  • In the literal version above? or in your attempt at adding the other fields to that approach? If it's the latter, make sure to escape all quotation marks (\" instead of ") like those in ` – Robot Woods Mar 29 '11 at 20:19
  • remove the line breaks, or break it up into multiple field+= statements – Robot Woods Mar 29 '11 at 20:55
  • okay. Is my code correct except line break? There is php script – Behind the screen Mar 29 '11 at 21:00
  • for the calendar, remove that piece from the loop. For the item type, I'm not sure, why don't you post your full code above – Robot Woods Mar 30 '11 at 00:32
  • not working. even after removing java script code from the loop. Its only create a textbox named txtdate. and how can I post my php code above. If I post that will not work – Behind the screen Mar 30 '11 at 08:46
  • I have added the code to my question. except these code all are same. I only wants that whenever I add fields date fields must contain date picker. when I open the page date picker is on the place, but when I add field, It only add textbox not calendar. – Behind the screen Mar 30 '11 at 14:25
  • You're still not posting your whole code. I have tried putting your items back together, but I think you've left out some functions. Take a look at my latest version above, but you'll need to add whatever you left out – Robot Woods Mar 30 '11 at 15:37
  • Sorry, I have uploaded a file to my domain please take a look on http://bit.ly/g5UWvj I have code in two part 1 is php file and 1 is js file where function written – Behind the screen Mar 30 '11 at 16:07
  • I just used the jQuery UI datepicker instead – Robot Woods Mar 30 '11 at 19:23
  • all works good Robot Woods. Thank you so much for the help. Only 1 small problem is there. It not works with IE. It gives me error on console is SCRIPT601: Unknown runtime error at document.getElementById("f").innerHTML=fields; – Behind the screen Mar 30 '11 at 21:16
  • find the line `var fields+=" – Robot Woods Mar 31 '11 at 00:53
  • I know, I am irritating you now. but I have 1 more problem, How can I validate this form. thanks – Behind the screen Mar 31 '11 at 13:11
  • change the submit button to fire some other function onclick, and in that function, do whatever validation you need, and if all tests succeed, then you `document.forms["frmaddservice"].submit();` – Robot Woods Mar 31 '11 at 13:16
  • Hi I am trying to validate all fields. It will work for check blank fields but when I check for numeric, its not working. :-( I have posted my validation code here – Behind the screen Mar 31 '11 at 17:53
  • I think you should accept this answer, and post the validation question as a new one so that more people see it and you'll get the best guidance. (after searching here to make sure it hasn't already been answered). I am still learning myself, so I am sure others will give you a better answer...like this maybe: http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric – Robot Woods Mar 31 '11 at 18:00
0

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

<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:

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:

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:

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.

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

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

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