[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

dynamic button & php

Posted on 2011-10-06
16
Medium Priority
?
327 Views
Last Modified: 2013-12-12
Hey guys,

I'm new in html and php so, sorry if my question seems clear and easy! Anyway, In my table I've a problem with dynamic Buttons! I'm trying to create a dynamic buttons each with same id+1 (starting from id 1) and I want to sent the data from also dynamic textfield to my database! Knowing that I'm using javascript to generate these buttons and fields and jQuery to parse the data to .php file (if there is easiest way please help me!).

Here is a part of my code..
using javascript i generate a button:

var cell8 = row.insertCell(8);
var itAd = document.createElement('input');
itAd.setAttribute('type', 'submit');
itAd.setAttribute('name', INPUT_NAME_PREFIX + iteration);
itAd.style.width = "100%";
itAd.setAttribute('value', "Add");
itAd.id="add"+iteration;

itAd.setAttribute('onclick', 'addRowToTable()');

$(document).ready(function(){
                $("div#msgbox").hide();
                $("#add".iteration).click(function() {
                       $.post('insert.php', {
                            proid: $("#proid".iteration).val(),
                            brand: $("#brand".iteration).val()
                      },
                      function(response){
                            $("div#msgbox #msg").html("Item added successfully..");
                            $("div#msgbox").hide().slideDown("normal");
                           
                        }
                    );
                return false;
            });
            $("div#msgbox").click(function(){
            $(this).slideUp("normal");
                })
            });


The HTML code is:
<table border=1 id="item_Table" width=73%>
            <tr>
                <th style="width:4%; size:20px;">#</th>
                <th style="width:10%; size: 5px">Product ID</th>
                <th style="width:10%; size: 5px">Brand</th>
                <th style="width:4%"></th>
            </tr>
        </table>
0
Comment
Question by:s3adcom
  • 9
  • 7
16 Comments
 
LVL 83

Expert Comment

by:leakim971
ID: 36932442
add this (in bold) :
var cell8 = row.insertCell(8);
var itAd = document.createElement('input');
itAd.setAttribute('type', 'submit');
itAd.setAttribute('name', INPUT_NAME_PREFIX + iteration);
itAd.style.width = "100%";
itAd.setAttribute('value', "Add");
itAd.id="add"+iteration;
itAd.className = "addButton";

and replace :
$("#add".iteration).click(function() {
by :
$(".addButton").live("click", function() {

more info : http://api.jquery.com/live/
0
 
LVL 83

Expert Comment

by:leakim971
ID: 36932470
hmm... I miss the point you want to post the right data, so use :

                $(".addButton").live("click", function() {
                       $.post('insert.php', {
                            var iteration = $(this).attr("id").replace("itAd","");
                            proid: $("#proid" + iteration).val(),
                            brand: $("#brand" + iteration).val()
                      },
                      function(response){
                            $("div#msgbox #msg").html("Item added successfully..");
                            $("div#msgbox").hide().slideDown("normal");
                           
                        }
                    );
                return false;
            });
0
 
LVL 83

Expert Comment

by:leakim971
ID: 36932480
sorry correction :

                $(".addButton").live("click", function() {
                       var iteration = $(this).attr("id").replace("itAd","");
                       $.post('insert.php', {
                            proid: $("#proid" + iteration).val(),
                            brand: $("#brand" + iteration).val()
                      },
                      function(response){
                            $("div#msgbox #msg").html("Item added successfully..");
                            $("div#msgbox").hide().slideDown("normal");
                           
                        }
                    );
                return false;
            });
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 83

Expert Comment

by:leakim971
ID: 36932489
this line :
var iteration = $(this).attr("id").replace("itAd","");

help us to retrieve the iteration from the button ID, we replace itAd by nothing
0
 

Author Comment

by:s3adcom
ID: 36933134
Thanks for answering my question, but I still have one problem which is I can't access the page "insert.php". It seems that the $.post doesn't work correctly! I tried to put it in the <form> and out of it but still facing the same problem!

Again thanks and hope you can help me on this..
0
 
LVL 83

Expert Comment

by:leakim971
ID: 36933320
please provide a link to your page
0
 

Author Comment

by:s3adcom
ID: 36933363
Attached is my page! Thanks a lot for your help. InventoryManagement.php
0
 
LVL 83

Expert Comment

by:leakim971
ID: 36933419
everything run fine on my side
I asked a link to your page to see it running not the source
0
 

Author Comment

by:s3adcom
ID: 36933550
I'm running my code in locally, where "insert.php" is just print anything just to make sure it goes there, because now nothing happen if when I call it! Though, not sure what you mean.
0
 
LVL 83

Expert Comment

by:leakim971
ID: 36933571
0
 

Author Comment

by:s3adcom
ID: 36933584
Yes this is work fine! however, I want to add these fields to my db and first I want to know if the $.post works or not when I click on "Add" button. It seems that $.post doesn't go to "insert.php"!! Just to make it clear, the "Add" button should insert the row to my db and also add new row in my table.
0
 
LVL 83

Expert Comment

by:leakim971
ID: 36933621
replace :
itTp.id="Type"+iteration;
by :
itTp.id="type"+iteration;

and replace :
                    var iteration = $(this).attr("id").replace("itAd","");
by :
                    var iteration = $(this).attr("id").replace("add","");

it will work
0
 

Author Comment

by:s3adcom
ID: 36933715
I'm sorry, but its not working!
Really thank you for your time and cooperation, means a lot!
0
 
LVL 83

Accepted Solution

by:
leakim971 earned 2000 total points
ID: 36933727
Tested locally it work
You may have an error on the server
don't forget each time field name have an iteration number after its name

so you can't use : $_POST['type'];
but something like : $_POST['type2'];
<!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>Inventory Management</title>
    <style>
    #item_Table, td, tr{
        margin:auto;
        border-color:black;
        padding: 0.1em;
    }
    .classy0 { background-color: #666666; color: #999999; }
    .classy1 { background-color: #999999; color: #666666; }
    
    .header { background-color: #9A2211; color: #FFFFFF; }
    
    div#msgbox {background: #9A2211; border-bottom: 2px solid #000000; color: #FFFFFF; width: 200px; height: 25px; position: absolute; top: 0; left: 0; right: 0px; cursor: pointer;}
    div#msgbox #msg {line-height: 30px; padding-left: 10px;}
    
    </style>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
    var timerID = null;
    var timerRunning = false;
    
    var INPUT_NAME_PREFIX = 'inputName';
    var TABLE_NAME = 'item_Table';
    var ROW_BASE = 1;
    var hasLoaded = false;
    
    window.onload=fillInRows;
    
    // *************************** Clock!
    
    function fillInRows()
    {
        hasLoaded=true;
        startclock();
        addRowToTable();
    }
    
    function stopclock(){
        if(timerRunning)
        clearTimeout(timerID);
        timerRunning = false;
    }
        
        function showtime() {
        var now = new Date();
        var hours = now.getHours();
        var minutes = now.getMinutes();
        var seconds = now.getSeconds()
        var timeValue = "" + ((hours >12) ? hours -12 :hours)
        if (timeValue == "0") timeValue = 12;
        timeValue += ((minutes < 10) ? ":0" : ":") + minutes
        timeValue += ((seconds < 10) ? ":0" : ":") + seconds
        timeValue += (hours >= 12) ? " P.M." : " A.M."
        document.clock.clock.value = timeValue;
        timerID = setTimeout("showtime()",1000);
        timerRunning = true;
    }

    function startclock() {
        stopclock();
        showtime();
    }
        
    //************************************ Table!
        
    function myRowObject(one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve)
    {
        this.one = one;
        this.two = two;
        this.three = three;
        this.four = four;
        this.five = five;
        this.six = six;
        this.seven = seven;
        this.eight = eight;
        this.nine = nine;
        this.ten = ten;
        this.eleven = eleven;
        this.twelve = twelve;
    }
    
    function addRowToTable(num)
    {
        if (hasLoaded) {
            var tbl = document.getElementById(TABLE_NAME);
            var nextRow = tbl.tBodies[0].rows.length;
            var iteration = nextRow + ROW_BASE;
            
            if (num == null) {
                    num = nextRow;
            } else {
                    iteration = num + ROW_BASE;
            }
            
            var row = tbl.tBodies[0].insertRow(num);
            
            row.className = 'classy' + (iteration % 2);
            
            var cell0 = row.insertCell(0);
            var textNode = document.createTextNode(iteration);
            
            var cell1 = row.insertCell(1);
            var itId = document.createElement('input');
            itId.setAttribute('type', 'text');
            itId.setAttribute('name', INPUT_NAME_PREFIX + iteration);
            itId.style.width = "100%";
            
            itId.id = "proid"+iteration;
            
            //itId.setAttribute('size', '10');
            //itId.setAttribute('value', iteration); // iteration included for debug purposes
            
            var cell2 = row.insertCell(2);
            var itBr = document.createElement('input');
            itBr.setAttribute('type', 'text');
            itBr.setAttribute('name', INPUT_NAME_PREFIX + iteration);
            itBr.style.width = "100%";
            itBr.id="brand"+iteration;
            //itBr.setAttribute('size', '10');
            //itBr.setAttribute('value', iteration); // iteration included for debug purposes
            
            var cell3 = row.insertCell(3);
            var itTp = document.createElement('input');
            itTp.setAttribute('type', 'text');
            itTp.setAttribute('name', INPUT_NAME_PREFIX + iteration);
            itTp.style.width = "100%";
            itTp.id="type"+iteration;
            //itTp.setAttribute('size', '40');
            //itTp.setAttribute('value', iteration); // iteration included for debug purposes
            
            var cell4 = row.insertCell(4);
            var itCl = document.createElement('input');
            itCl.setAttribute('type', 'text');
            itCl.setAttribute('name', INPUT_NAME_PREFIX + iteration);
            itCl.style.width = "100%";
            itCl.id="color"+iteration;
            //itCl.setAttribute('size', '5');
            //itCl.setAttribute('value', iteration); // iteration included for debug purposes
            
            var cell5 = row.insertCell(5);
            var itSz = document.createElement('input');
            itSz.setAttribute('type', 'text');
            itSz.setAttribute('name', INPUT_NAME_PREFIX + iteration);
            itSz.style.width = "100%";
            itSz.id="size"+iteration;
            //itSz.setAttribute('size', '10');
            //itSz.setAttribute('value', iteration); // iteration included for debug purposes

            var cell6 = row.insertCell(6);
            var itPr = document.createElement('input');
            itPr.setAttribute('type', 'text');
            itPr.setAttribute('name', INPUT_NAME_PREFIX + iteration);
            itPr.style.width = "100%";
            itPr.id="price"+iteration;
            //itPr.setAttribute('size', '10');
            //itPr.setAttribute('value', iteration); // iteration included for debug purposes
            
            var cell7 = row.insertCell(7);
            var itQn = document.createElement('input');
            itQn.setAttribute('type', 'text');
            itQn.setAttribute('name', INPUT_NAME_PREFIX + iteration);
            itQn.style.width = "100%";
            itQn.id="quantity"+iteration;
            //itQn.setAttribute('size', '10');
            //itQn.setAttribute('value', iteration); // iteration included for debug purposes
            
            var cell8 = row.insertCell(8);
            var itAd = document.createElement('input');
            itAd.setAttribute('type', 'submit');
            itAd.setAttribute('name', INPUT_NAME_PREFIX + iteration);
            itAd.style.width = "100%";
            //itAd.setAttribute('size', '10');
            itAd.setAttribute('value', "Add"); // iteration included for debug purposes
            itAd.id="add"+iteration;
            itAd.className = "addButton";
            
            //itAd.setAttribute('onchange', this.value);
            
            itAd.setAttribute('onclick', 'addRowToTable()');
            
            var cell9 = row.insertCell(9);
            var itEd = document.createElement('input');
            itEd.setAttribute('type', 'button');
            itEd.setAttribute('name', INPUT_NAME_PREFIX + iteration);
            itEd.style.width = "100%";
            //itEd.setAttribute('size', '10');
            itEd.setAttribute('value', "Edit"); // iteration included for debug purposes
            itEd.id="edit"+iteration;
            
            var cell10 = row.insertCell(10);
            var itDt = document.createElement('input');
            itDt.setAttribute('type', 'button');
            itDt.setAttribute('name', INPUT_NAME_PREFIX + iteration);
            itDt.style.width = "100%";
            //itDt.setAttribute('size', '10');
            itDt.setAttribute('value', "Delete"); // iteration included for debug purposes
            itDt.id="delete"+iteration;
            
            itDt.setAttribute('onclick', 'deleteChecked()');
            
            var cell11 = row.insertCell(11);
            var itCk = document.createElement('input');
            itCk.setAttribute('type', 'checkbox');
            itCk.setAttribute('name', INPUT_NAME_PREFIX + iteration);
            //itCk.style.width = "100%";
            
            cell0.appendChild(textNode);
            cell1.appendChild(itId);
            cell2.appendChild(itBr);
            cell3.appendChild(itTp);
            cell4.appendChild(itCl);
            cell5.appendChild(itSz);
            cell6.appendChild(itPr);
            cell7.appendChild(itQn);
            cell8.appendChild(itAd);
            cell9.appendChild(itEd);
            cell10.appendChild(itDt);
            cell11.appendChild(itCk);
            
            row.myRow = new myRowObject(textNode, itId, itBr, itTp, itCl, itSz, itPr, itQn, itAd, itEd, itDt, itCk);
            
            if(iteration>2)
            {
                //alert("Iteration "+ INPUT_NAME_PREFIX + iteration);
                document.getElementById("add"+(iteration-1)).disabled = true;
            }
            
            $(document).ready(function(){
                $("div#msgbox").hide();
                $(".addButton").live("click", function(){
                    var iteration = $(this).attr("id").replace("add","");
                    $.post('insert.php', {
                        //alert("Hello");
                        proid: $("#proid"+iteration).val(),
                        brand: $("#brand"+iteration).val(),
                        type: $("#type"+iteration).val(),
                        color: $("#color"+iteration).val(),
                        size: $("#size"+iteration).val(),
                        price: $("#price"+iteration).val(),
                        quantity: $("#quantity"+iteration).val()
                        },
                        function(response){
                            $("div#msgbox #msg").html("Item added successfully..");
                            $("div#msgbox").hide().slideDown("normal");
                            
                            //alert("Done: " + INPUT_NAME_PREFIX + iteration);   
                        }
                    );
                return false;
            });
            $("div#msgbox").click(function(){
            $(this).slideUp("normal");
                })
            });
        }
    }
        
    function deleteChecked()
    {
        if (hasLoaded) {
                var checkedObjArray = new Array();
                var cCount = 0;
        
                var tbl = document.getElementById(TABLE_NAME);
                
                for (var i=0; i<tbl.tBodies[0].rows.length; i++) {
                        if (tbl.tBodies[0].rows[i].myRow && tbl.tBodies[0].rows[i].myRow.twelve.getAttribute('type') == 'checkbox' && tbl.tBodies[0].rows[i].myRow.twelve.checked) {
                                //alert("NOOOO");
                                checkedObjArray[cCount] = tbl.tBodies[0].rows[i];
                                cCount++;
                        }
                }
                if (checkedObjArray.length > 1)
                    alert("Check only one row to delete..");
                else if(tbl.tBodies[0].rows[tbl.rows.length-1].myRow.twelve.checked)
                        alert("You can not delete last row..");
                    else{
                            var rIndex = checkedObjArray[0].sectionRowIndex;
                        
                            for (var i=0; i<checkedObjArray.length; i++) {
                                var rIndex = checkedObjArray[i].sectionRowIndex;
                                checkedObjArray[i].parentNode.deleteRow(rIndex);
                            }
                        //deleteRows(checkedObjArray);
                        reorderRows(tbl, rIndex);
                        }
        }
    }
    
    function reorderRows(tbl, startingIndex)
    {
	if (hasLoaded) {
		if (tbl.tBodies[0].rows[startingIndex]) {
			var count = startingIndex + ROW_BASE;
                        
			for (var i=startingIndex; i<tbl.rows.length; i++) {
                            tbl.tBodies[0].rows[i].myRow.one.data = count; // text
                            
                            tbl.tBodies[0].rows[i].myRow.two.name = INPUT_NAME_PREFIX + count;
                            tbl.tBodies[0].rows[i].myRow.three.name = INPUT_NAME_PREFIX + count;
                            tbl.tBodies[0].rows[i].myRow.four.name = INPUT_NAME_PREFIX + count;
                            tbl.tBodies[0].rows[i].myRow.five.name = INPUT_NAME_PREFIX + count;
                            tbl.tBodies[0].rows[i].myRow.six.name = INPUT_NAME_PREFIX + count;
                            tbl.tBodies[0].rows[i].myRow.seven.name = INPUT_NAME_PREFIX + count;
                            tbl.tBodies[0].rows[i].myRow.eight.name = INPUT_NAME_PREFIX + count;
                            
                            tbl.tBodies[0].rows[i].myRow.nine.id = "add" + count;
                            tbl.tBodies[0].rows[i].myRow.ten.id = "edit" + count;
                            tbl.tBodies[0].rows[i].myRow.eleven.id = "delete" + count;

                            tbl.tBodies[0].rows[i].myRow.twelve.name = INPUT_NAME_PREFIX + count;
                            
                            tbl.tBodies[0].rows[i].className = 'classy' + (count % 2);
                            
                            count++;
			}
		}
	}
    }
    </script>
</head>
<body bgcolor="FFFFBA">
    <div id="msgbox" style="margin-top:0px; margin-left:215px; margin-right:500px;"><span id="msg"></span></div>
    <div style="margin-top:30px; margin-left:215px; margin-right:500px;">
        <form name="clock" >
            <div><font size="2">Welcome admin...</font></div>
            <font size="2">Current time:</font><input type="text" name="clock" style="border: 0px; color:red; background:FFFFBA" size=12 value="">
        </form>
    </div>
    <div style="margin-top:10px; margin-bottom:1px; margin-left:215px; margin-right:500px;"><font size="2" color="red">* To Edit or Delete an Item, please make sure you select it first!</font></div>
    <div style="margin-top:5px; margin-left:50px; margin-right:50px;">
        <form name="fTable" id="fTable">
        <table border=1 id="item_Table" width=73%>
            <tr>
                <th style="width:4%; size:20px;">#</th>
                <th style="width:10%; size: 5px">Product ID</th>
                <th style="width:10%; size: 20px">Brand</th>
                <th style="width:10%">Type</th>
                <th style="width:10%">Color</th>
                <th style="width:10%">Size</th>
                <th style="width:10%">Price</th>
                <th style="width:10%">Quantity</th>
                <th style="width:4%"></th>
                <th style="width:4%"></th>
                <th style="width:4%"></th>
                <th style="width:4%"></th>
            </tr>
        </table>
        
    </div>
</body>

    </form>
</html>

Open in new window

0
 

Author Comment

by:s3adcom
ID: 36933824
Thank you very much!! It works now.
0
 

Author Closing Comment

by:s3adcom
ID: 36933832
End up following this guy!
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

OverviewThis article demonstrates a simple search form using AJAX. The purpose of the article is to demonstrate how to use the same code to render a page and javascript (JQuery) and AJAX to make subsequent calls to refine the results. The princip…
This article discusses how to implement server side field validation and display customized error messages to the client.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question