Hi guys, I have an HTML page that I built and at the moment the content on it gets changed via javascript. What I would like to achieve is to change the content permanently on this page (which will be uploaded to the server).
Now, I must admit that I have very little experience with PHP but I use javascript on a regular basis and I know a bit of JAVA too, I hope these skills might be useful. The only experience with PHP I had was ages ago when I built a small form.
So, here is the code, it might be useful to see it I think:
HTML

<!DOCTYPE html>
<html>
    <head>
        <title>This is a test</title>
        <link rel="stylesheet" type="text/css" href="styles.css" >
        <script src="http://code.jquery.com/jquery.js"></script>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
        <table>
            <tr>
                <th>Week ending</th>
                <th>Total week hours worked</th>              
                <th>Week overtime available</th>
                <th>Total overtime</th>
                <th>Comments</th>             
            </tr>
            <tr class="editable">
                <td><input type="text" class="date"></td>
                <td> <input type="text" class="hoursWorked"></td>
                <td class="overtimeAvailable"> </td>              
                <td class="totalOvertime"></td>
                <td> <textarea type="text" class="comments"></textarea></td>                
            </tr>            
        </table>
        <button>Submit</button>
    </body>
</html>

Javascript

$(document).ready(function(){
    var totalOvertime = 0;
    $("button").click(function(){
        var tableRow;
        var date;
        var hoursWorked;
        var overtimeAvailable;
        var comment;
        date = $("input.date").val();
        //console.log(date);
        hoursWorked = parseFloat($("input.hoursWorked").val());
        overtimeAvailable = hoursWorked - 37.5;
        totalOvertime += overtimeAvailable;
        comment = $(".comments").val();
        console.log(comment);
        console.log("hours " + typeof hoursWorked + " overtime " + typeof overtimeAvailable );
        tableRow = '<tr>' +
                        '<td class="date">' + date + '</td>' +
                        '<td class="hoursWorked">' + hoursWorked + '</td>' +
                        '<td class="overtimeAvailable">' + overtimeAvailable + '</td>' +
                        '<td class="totalOvertime">' + totalOvertime + '</td>' +
                        '<td class="comments">' + comment + '</td>' +
                    '</tr>';
        $(".editable").before(tableRow);
        /* $(".overtimeAvailable").each(function(){
            totalOvertime = totalOvertime + overtimeAvailable;
            $(".totalOvertime").html(totalOvertime + " hrs");
        }); */
        $("input, textarea").val("");//clear input
    });
});

The way this is working at the moment is that the user type the data in the input fields and then when the submit button is clicked the page is populated. As I said before I'd like to change the page and make those changes permanent. Can anybody give me any indication of how this can be achieved please and what I need?
thanks

Recommended Answers

All 23 Replies

So to get you started on the right track, you will need a form on this page. Meaning, your input elements will need to be within the form. Once the user submits the form, you will send the data to another page running your PHP code.

Here is an example....just an example for discussion purposes...

<form action="process.php" method="post">
  Name: <input type="text" name="date"><br />
  E-mail: <input type="text" name="hours"><br />
  <input type="submit">
</form>

Now on the process.php page, you can retrieve the data was submitted. In this example, we just show the data back on the screen. However, in your case, your next step would be to connect to a database and insert the data into a table.

<body>

   Date: <?php echo $_POST["date"]; ?><br />
   Hours: <?php echo $_POST["hours"]; ?>

</body>

In your case, since you are doing some client side stuff first, you can have the button submit the form after you have completed your processing. So in your script, you would likely include this at the end... $("#formName").submit();

I'd recommend that you first get familiar with how to post data from a form and retrieve that data on the target page. Then we can move on to processing/storing the data in a DB. yes/no?

Hi JorgeM, thanks for that. Yes, it sounds good to me.
I have amended the html to include the form and I will now play around with posting data and retrieving it as per your example. I will come back to you soon.
In general terms, I know ery very little about SQL - and PHP for that matter - I just played around with a few statements time and time ago, but happy to give it a go but definitely need some help.

One more question before I set off. In my PHP file, do I need any doctype, anything at all, or can I just start the way you did with a body tag?
thanks

Ah sorry, forgot to ask. SOme of the fields are not input fields, like the <td

class="overtimeAvailable"> </td>
                    <td class="totalOvertime"></td>

even if they sit inside a form. Do they have to be converted in input fields or can they remain tds when it comes down to send/retrive data from the server?

So a PHP file is going to include a mix of HTML and PHP code. You can start by creating a new .php file and populate that file with your standard HTML code, including DOCTYPE and the typical elements (html, head, body).

Where ever you want to introduce PHP code, you do so by enclosing the code within <?php ... ?> this block of syntax.

If your web server is configured to run PHP code, the PHP engine will parse the .PHP file when it is called, then process the PHP code in that page and create the appropriate HTML to send back to the requesting user agent.

Here is an example of "Hello World" in a .php file.

<!DOCTYPE html>
<html>
<head>
 <title>Hello World</title>
</head>
<body>
 <h1>My first PHP Page</h1>
 <?php

   echo ("Hello World!");

 ?>
 <p>I can mix HTML and PHP code...</p>
</body>
</html>

You can quickly start your way by taking a look at the PHP online manual http://www.php.net/manual/en/index.php

There are lots of sites that have some beginner tutorials as well...

With regard to your question about table data, that is great for displaying data but if you want to POST data to another page using a form, you'll need input elements to do so. If you want to pass data without actually displaying it in the browser, its common to use an input element of type hidden.

Also, your question about getting data into the database is a common topic on this site... here is a discussion going on right now you can take a look at to get familiar. data is posted from a form, then retrieved to be inserted into a DB record.

http://www.daniweb.com/web-development/php/threads/467217/echo-result-from-database

Hi, Hi thanks for the info.

I had a quick look at the PHP guide, Is there any topic in particular that I should look up in there?

I also had a look at the database discussion...there is quite a bit of code that I don't understand...anyway.

I had a go at what you suggested.

I have created a php file action.php:

<!DOCTYPE html>

<html>

                <head>

                                <title>Hello World</title>

                                <link rel="stylesheet" type="text/css" href="styles.css" >

                </head>

                <body>

                                Date:<?php echo $_POST["the_date"]; ?>

                                Hours worked:<?php echo $_POST["the_hours_worked"]; ?>

                                Comment:<?php echo $_POST["the_comments"]; ?>

                </body>

</html>              

I have changed the HTML code accordingly:

...

                <form action="action.php" method="post" id="theForm">

                                                <table>

                                                                <tr>

                                                                                <th>Week ending</th>

                                                                                <th>Total week hours worked</th>                                                      

                                                                                <th>Week overtime available</th>

                                                                                <th>Total overtime</th>

                                                                                <th>Comments</th>                                                   

                                                                </tr>

                                                                <tr class="editable">

                                                                                <td class="editableField"><input type="text" class="date" placeholder="Date" name="the_date"></td>

                                                                                <td class="editableField"> <input type="text" class="hoursWorked" placeholder="Hours worked" name="the_hours_worked"></td>

                                                                                <td class="overtimeAvailable"><input type="hidden" class="overtimeInput"></td>

                                                                                <td class="totalOvertime"><input type="hidden" class="totalOvertimeInput"></td>

                                                                                <td class="editableField"> <textarea type="text" class="comments" placeholder="Insert comment" name="the_comments"></textarea></td>

                                                                </tr>                                    

                                                </table>

                                                <button>Submit</button>

                                </form>



...

And the javascript:

...

$(".editable").before(tableRow);

                                /* $(".overtimeAvailable").each(function(){

                                                totalOvertime = totalOvertime + overtimeAvailable;

                                                $(".totalOvertime").html(totalOvertime + " hrs");

                                }); */

                                $("input, textarea").val("");//clear input

                                $("#theForm").submit();             

                });

});

Now, I have tried at work and the action.php page doesn't display the data returned...not sure why, everything seems to be as it should.
I have tried at home http://antobbo.webspace.virginmedia.com/overtime/overtime.html and I get a 500 PWP error that I can't explain because I am fairly sure V irgin serves do support PHP(I have used it before.)

So, rather than trying to figure out the exact problem with your example, i put together a really simply example and tested it. works as expected.

form.php
<!DOCTYPE html>
<html>
<body>
<form action="action.php" method="post" id="theForm">
<table>
<tr>
 <th>Week ending</th>
 <th>Total week hours worked</th>
 <th>Comments</th>
</tr>
<tr class="editable">
 <td class="editableField"><input type="text" class="date" placeholder="Date" name="the_date"></td>
 <td class="editableField"><input type="text" class="hoursWorked" placeholder="Hours worked" name="the_hours_worked"></td>
 <td class="editableField"><textarea type="text" class="comments" placeholder="Insert comment" name="the_comments"></textarea></td>
</tr>
</table>
<input type="submit" text="Submit" />
</form>
</body>
</html>
action.php
<!DOCTYPE html>
<html>
<body>

Date: <?php echo $_POST["the_date"]; ?><br />
Hours: <?php echo $_POST["the_hours_worked"]; ?><br />
Comments: <?php echo $_POST["the_comments"]; ?>

</body>
</html>

This is the most basic example I can come up with that should at least give you the ability to try it out and experiment. The idea here is to capture input information within a form, post it, then retrieve the form data on the target page.

As the processing on the target page gets more complex, you can create a block of PHP code at the top of the page (before the doctype declaration) and collect all of the data, assign it to variables, etc.. Then use the variables within your page accordingly such as inserting/updating records, display data back to the user, send an email message, etc...

Here is a link to the demo >> http://itg.somee.com/dw/dw-467433/

thanks for that. I wonder what I got wrong on mine then..well nevermind, although yours returned the same error a few times, it got better only after a few crtl f5. Anyway, I will play around with that and try to fix mine too. So from what you are saying I understand that I can use php variables and javascript ones at the same time?

although yours returned the same error a few times, it got better only after a few crtl f5.

I placed those demos on a free hosting platform.. You (me) get what you pay for.. sorry about that. //EDIT -- I moved the page to a better hosting platform.

So from what you are saying I understand that I can use php variables and javascript ones at the same time?

They can be on the same page, absolutely. But they arent being used at the same time. Your javascript is being handled client side. When you submit the page, your PHP code is processed server side.

From the client side, you will never see the PHP code (click on view source) because the php engine is processing the php code and generating HTML.

Oh sorry I didn't mean to be annoying about the error, I just noticed and so I mentioned it.
Oh by the way I figured out what was wrong with my code.
1)the virgin media server seems to have problems with PHP. I transferred the page to a different domain and it worked, the 500 error disappeared. What was preventing the PHP page to bring back the content was the button. The moment I replaced the <button> tag with an <input type="submit"> the PHP page worked a treat and brought back the values. Why this is I don't know, I am not skilled enough in PHP.
SO, I will play around a bit with this, and leave this thread open, I am sure I will post back
thanks

Oh sorry I didn't mean to be annoying about the error, I just noticed and so I mentioned it.

No worries, I've been testing out different free hosting providers so I can upload demos,etc.. and many of them are junk, at least for the free services they provide. I updated the link above, this provider seems to be working fine.

Good news.. yes you can work off of this thread as you continue your progress.... there are other very skilled PHP members on this site that I'm sure will help as well.

thanks. Sorry one more question so I get this clear in my head. After the form is submitted, the page action.php is displayed. Now, I want the html page to change not the action.php. I want to have what the user has input to be displayd permanently on the HTML page so should I do something similar to this and update the php page with the code that is on the HTML page?
action.php (which works nicely although I don't think this is the way forward)

<!DOCTYPE html>
    <html>
        <head>
            <title>Hello World</title>
            <link rel="stylesheet" type="text/css" href="styles.css" >
        </head>
        <body>
            <table>
                    <tr>
                        <th>Week ending</th>
                        <th>Total week hours worked</th>              
                        <th>Week overtime available</th>
                        <th>Total overtime</th>
                        <th>Comments</th>             
                    </tr>
                    <tr class="editable">
                        <td class="editableField">Date:<?php echo $_POST["the_date"]; ?></td>
                        <td class="editableField">Hours worked:<?php echo $_POST["the_hours_worked"]; ?></td>
                        <td class="overtimeAvailable"><input type="hidden" class="overtimeInput"></td>
                        <td class="totalOvertime"><input type="hidden" class="totalOvertimeInput"></td>
                        <td class="editableField">Comment:<?php echo $_POST["the_comments"]; ?></td>
                    </tr>            
                </table>




        </body>
    </html>  

Also, I take that what my js script does (create a table on the fly) is not needed anymore. So what should my js script do? Will PHP take care of this aspect or does it somehow take the data and injects it into the HTML page?

After the form is submitted, the page action.php is displayed. Now, I want the html page to change not the action.php.

So it sounds like you want to post to the same page. That's fine you can do that too.

I want to have what the user has input to be displayd permanently on the HTML page so should I do something similar to this and update the php page with the code that is on the HTML page?

When you say permanently...lets clarify what is actually happening when a request is made. A request is made to the web server for content. The request could be for an file with an extension of .html, .htm, .php, etc.. The web server is going to grab that file and send back HTML to the user agent (browser). There is nothing really permanent in that process. Each time a request is made, the server sends back HTML. If its a PHP file, the HTML sent back to the browser can change because now you are including logic in the PHP file that can alter the response. When it comes to HTML, there is no logic so the response is always the same.

If you only want to work with one page, again, you can do that. That would mean that your form.html page needs to be form.php and you simply update the form element's action attribute to post to itself. You then need to update your PHP code appropriate to show whatever content you wish based upon where you are in the logic process/work flow. This can be done with if..else statements for example and other programming concepts you are probably familiar with.

Also, I take that what my js script does (create a table on the fly) is not needed anymore. So what should my js script do? Will PHP take care of this aspect or does it somehow take the data and injects it into the HTML page?

Ok, so as you are aware, javascript is basically client side code. PHP on the other hand is server side code. In many cases, what you can do client side, such as a calculation (adding two numbers) can be done client side with javascript, correct? Well, of course, you can do the same server side with PHP. The difference is that if you want PHP to do the calculation, you have to send a request back (POST back) to the PHP page, process, and send the results back to the browser. Not so nice from a user experience, espcially if all you need to do is add two numbers together.

Keep in mind that not everything you can do with javascript can be done server-side with PHP. Think about all of the cool stuff javascript and other libraries (jQuery) can do with regard to say animation, things that can only be done where a post back would break the process.

I really didnt take a close look at your javascript code, the formatting above was very hard to read and understand. If you want to perform calculations, it can be done client or server side. Its up to you. If you do it client side, you need to assign the results to input elements within the form so that when you post the page, you can read the values from your PHP code.

thank you, things are a little clearer now :-).
Sorry for the code formatting, something must have gone a bit wonky there (I think it's the indentation of the text file that caused problems ).
Anyway, I sort of experimented a bit with retrieving data from the php file, it seems reasonable enough. Further from what you were saying, I changed my form page from HTML to PHP extension and post back to itself like so:
overtime.php

<!DOCTYPE html>
<html>
<head>
<title>This is a test</title>
<link rel="stylesheet" type="text/css" href="styles.css" >
<script src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form action="overtime.php" method="post" id="theForm">
<table>
<tr>
<th>Week ending</th>
<th>Total week hours worked</th>              
<th>Week overtime available</th>
<th>Total overtime</th>
<th>Comments</th>             
</tr>
<tr class="editable">
<td class="editableField"><input type="text" class="date" placeholder="Date" name="the_date"></td>
<td class="editableField"> <input type="text" class="hoursWorked" placeholder="Hours worked" name="the_hours_worked"></td>
<td class="overtimeAvailable"><input type="hidden" class="overtimeInput"></td>
<td class="totalOvertime"><input type="hidden" class="totalOvertimeInput"></td>
<td class="editableField"> <textarea type="text" class="comments" placeholder="Insert comment" name="the_comments"></textarea></td>
</tr>            
</table>
<!-- <button>Submit</button> -->
<input type="submit" text="Submit" />
</form>
</body>
</html>

Now, my javascript isn't really doing any animation as such, all it's doing is to add some HTML (so a bit more complex than calculation). If possible, I would like it to do it clientside simply because I am a bit more confident with this. Here is the script in a better format (hopefully):

$(document).ready(function(){

var totalOvertime = 0;
$("button").click(function(){
var tableRow;
var date;
var hoursWorked;
var overtimeAvailable;

var comment;

date = $("input.date").val();
//console.log(date);
hoursWorked = parseFloat($("input.hoursWorked").val());

overtimeAvailable = hoursWorked - 37.5;
totalOvertime += overtimeAvailable;
comment = $(".comments").val();
console.log(comment);
console.log("hours " + typeof hoursWorked + " overtime " + typeof overtimeAvailable );
tableRow = '<tr>' +
'<td class="date">' + date + '</td>' +
'<td class="hoursWorked">' + hoursWorked + '</td>' +
'<td class="overtimeAvailable">' + overtimeAvailable + '</td>' +
'<td class="totalOvertime">' + totalOvertime + '</td>' +
'<td class="comments">' + comment + '</td>' +
'</tr>';
$(".editable").before(tableRow);
/* $(".overtimeAvailable").each(function(){
totalOvertime = totalOvertime + overtimeAvailable;
$(".totalOvertime").html(totalOvertime + " hrs");
}); */
$("input, textarea").val("");//clear input
//$("#theForm").submit();   
});

});

The thing is that I can only modify the HTML after the server has processed the information input by the users in the HTML form, so I take the js script needs to run after. So, if you think it is useful, I was thinking to try to grab the information that the user has input on the same file, perhaps inserting - like you have mentioned a while back - a block of PHP at the top of the file and copy the data into some PHP variable. If not where do I go from here?
thanks

as you are doing Jquery you are almost there.

Change

<input type="submit" text="Submit" />

back to

<button id="butpress">Submit</button>

Then in your JQuery change

$("button").click(function()

to

$('#butpress').click(function()

So, let me ask a question here...

With your javascript, I see that you are adding HTML back on the screen to display to the user. Do you need user to review this info before the form is ultimately submitted back to the server for processing?

If so, I would think you would want two button then. The first to process the "hours" and the second to submit the form. The user would first fill out the form, click on a button to calculate, you show the user the results, then the user submits the form? Is that what you are trying to do?

If that is the case, when you create the additional HTML content within the form, you need to add input elements to store those values. Then when the form is submitted, we can use a block of PHP code to extract those values from the input elements.

Let me knwo if that is what you were envisioning..

Here is a quick example I put together from your code that simply allows you to fill out a few input elements, click a process button, performs some calculations, shows a submit button, then posts back, retrieves the post data and displays it back to the user.

This should help you get further in your efforts...

overtime.php
<!DOCTYPE html>
<html>
<head>
<title>This is a test</title>
<link rel="stylesheet" type="text/css" href="styles.css" >
<script src="http://code.jquery.com/jquery.js"></script>
</head>

<body>
<form action="overtime.php" method="post" id="theForm">
<table>
<tr>
<th>Week ending</th>
<th>Total week hours worked</th>              
<th>Week overtime available</th>
<th>Total overtime</th>
<th>Comments</th>             
</tr>
<tr class="editable">
<td class="editableField"><input type="text" class="date" placeholder="Date" name="the_date"></td>
<td class="editableField"> <input type="text" class="hoursWorked" placeholder="Hours worked" name="the_hours_worked"></td>
<td class="overtimeAvailable"><input type="text" disabled id="overtimeAvailable" name="overtimeAvailable" class="overtimeInput"></td>
<td class="totalOvertime"><input type="text" disabled id="totalOvertime" name="totalOvertime" class="totalOvertimeInput"></td>
<td class="editableField"><textarea type="text" class="comments" placeholder="Insert comment" name="the_comments"></textarea></td>
</tr>            
</table>
<button type="button" id="btnProcess">Process</button>
<input type="submit" id="btnSubmit" value="Submit" />
</form><br /><br/>

<?php
echo "Date: " . $_POST["the_date"] . "<br />";
echo "Hours Worked: " . $_POST["the_hours_worked"] . "<br />";
echo "Overtime Available: " . $_POST["overtimeAvailable"] . "<br />";
echo "Total Overtime: " . $_POST["totalOvertime"] . "<br />";
echo "Comments: " . $_POST["the_comments"] . "<br />";
?>


<script>
$(document).ready(function(){
 var totalOvertime = 0;
 $('#btnSubmit').hide();  
 $("#btnProcess").click(function(){
  var hoursWorked;
  var overtimeAvailable;
  hoursWorked = parseFloat($("input.hoursWorked").val());
  overtimeAvailable = hoursWorked - 37.5;
  totalOvertime += overtimeAvailable;

  $('#overtimeAvailable').val(overtimeAvailable);
  $('#totalOvertime').val(totalOvertime);
  $('#btnProcess').hide();
  $("input").removeAttr('disabled');
  $('#btnSubmit').val("Submit").show();  
 });
});
</script>

</body>
</html>

thanks guys, sorry for the delay.
@noelthefish I have noticed that if I change that to a button tag the PHP file doesn't work anymore, no idea why, happy yo try again
@JorgeM: I don't necessarily need a second button I don't think because the application will be used just by me. Anyway thanks for your code, I will play around with that a bit and let you know how things go :-)
thanks

JorgeM, I have had a really good look and played a bit with your code. I think things are clearer now, so thanks for the practical demonstration.
I want to practice a little more and modify my own PHP page, and made me wonder...I have seen how the php code and javascript can happily coexist, and in my case - I don't know if you remember - my script also created some HTML after hitting the submit button. You have showed me how to display the data returned by the php file. So, the problem for me now is that if my javascript creates the new table where the data returned by the PHP file will go, how do I get that data in the right place if the javascript and php happen at different times? So this is what happens:
Scenario 1:)I click the submit button and my script creates the variables and the new HTML table. Then the PHP returns some values. I could store those values in PHP variables but presumably I will need another script that runs after the PHP file, takes those variables and put them in the right place (ie in the table).
Scenario 2) I create another table in the html, make it invisible with css, then my script will make sure that after the submit button has been pressed the hidden table becomes visible again, the PHP returns the values but I still need to put them into some variables and then insert them in the right place in the table using another script (that again runs after the PHP code )?
thanks

if my javascript creates the new table where the data returned by the PHP file will go, how do I get that data in the right place if the javascript and php happen at different times?

JavaScript will always occur client side and PHP is unaware of this event occuring. PHP is server side, and JavaScript is unaware of it as well.

Its OK for JavaScript to add elements to the page. If your script adds input elements, make sure that you include an ID attribute and Name attribute on those input elements so you can access them from the PHP code like you would any other input element within the form.

So I'm having some difficulty following your scenarios, but let me explain it this way. I imagine you are having trouble figuring out how to pass values from the server to the client, manipulate the values and then get them back to the server. If you recall, thre are a few ways to get data from client to server. Lets just focus on the form method. Since you have a form, when you submit it, it sends data back to the server. This data came from the values stored in your form elements, mainly the input type elements.

If you change the value of these input elements (via JavaScript) prior to submitting the form, those values can be accessed server side using PHP. Once you are on your PHP side processing the data, you return whatever HTML content you choose back to the browser. This cycle continues.

If you want to store data client side and do not want to display it, but you do want to work with it and include this data in the form submission, you can add an input element of type hidden. <input id="some_id" name="some_name" type="hidden" />. You can assign a value to the hiddent input element via javascript like you would any other input element. When you submit the form, if this hidden element is within the form, you can access the value using PHP like you would any other input element.

thanks JorgeM. Sorry maybe I am making this extremely complicated. I am not sure why I am finding so difficult to explain what I want to do :-)! OK, so I think I will start changing my .php file and trying to do one by one all the things I want.
So - please bear with me - to start with, I'd like to add a row to the table that contains the tds and input fields where the user input will be inserted.
If this is the wrong approach then please let me know.

Its OK for JavaScript to add elements to the page. If your script adds input elements, make sure that you include an ID attribute and Name attribute on those input elements so you can access them from the PHP code like you would any other input element within the form.

So, I used javascript to do that but I am having problems, because when I hit submit, since the php page calls itself on submission and therefore 'reload' the page, the row is never inserted. However I have added the ids and names as you have suggested.
this is the HTML (I haven't added any php code as yet)

<!DOCTYPE html>
<html>
<head>
<title>This is a test</title>
<link rel="stylesheet" type="text/css" href="styles.css" >
<script src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form action="overtime.php" method="post" id="theForm">
<table>
<tr>
<th>Week ending</th>
<th>Total week hours worked</th>              
<th>Week overtime available</th>
<th>Total overtime</th>
<th>Comments</th>             
</tr>
<tr class="editable">
<td class="editableField"><input type="text" class="date" placeholder="Date" name="the_date"></td>
<td class="editableField"> <input type="text" class="hoursWorked" placeholder="Hours worked" name="the_hours_worked"></td>
<td class="overtimeAvailable"><input type="text" disabled class="overtimeInput"></td>
<td class="totalOvertime"><input type="text" disabled class="totalOvertimeInput"></td>
<td class="editableField"> <textarea type="text" class="comments" placeholder="Insert comment" name="the_comments"></textarea></td>
</tr>

</table>
<!-- <button>Submit</button> -->
<input type="submit" text="Submit" id="submission">
</form>
</body>
</html>

Javascript:

$(document).ready(function(){

var totalOvertime = 0;
$("#submission").click(function(){
var tableRow;
var date;
var hoursWorked;
var overtimeAvailable;

var comment;

date = $("input.date").val();
//console.log(date);
hoursWorked = parseFloat($("input.hoursWorked").val());

overtimeAvailable = hoursWorked - 37.5;
totalOvertime += overtimeAvailable;
comment = $(".comments").val();
console.log(comment);
console.log("hours " + typeof hoursWorked + " overtime " + typeof overtimeAvailable );
tableRow = '<tr>' +
'<td class="date" id="date" name="the_date_result"></td>' +
'<td class="hoursWorked" id="hoursWorked" name="the_hours_worked_result"></td>' +
'<td class="overtimeAvailable" id="overtimeAvailable" class="overtimeInput_result"></td>' +
'<td class="totalOvertime" id="totalOvertime" class="totalOvertimeInput_result"></td>' +
'<td class="comments" id="comments" name="the_comments_result"></td>' +
'</tr>';
$(".editable").before(tableRow);        
$("input, textarea").val("");//clear input
//$("#theForm").submit();   
});

});

So what I'm understanding is that you want to be able to add rows dynamically and perform some calculcations on each row.

Take a look at this recent discussion regarding adding rows dynamically to a table. The code may help you. I integrated some of that logic in your example..

http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/467834/auto-calculate

In the sample code below, i added an additional button, "add row". basically this button executes a function that adds a row to your existing table. One thing you will note is that unique ids were assigned to each element that is involved in the calculation process. this is because when we calculate, we need to be able to target specific input elements. So because of this, you need unique IDs.

Also, with regard to your question about PHP, there's no PHP code listed here, but that would be the next step. When you click on the submit button, you are posting back to the same page in this example. You can easily change that form action and post to another page. That is up to you. If you post to the same page, you need to include PHP code in the page that checks to see if the form was submitted, if it was, do your processing. Because you will now have many rows in the table, you will need to have some PHP logic to figure out how many items are in your form. Your form elements will be stored in arrays, so you can use a "for each" to go through the form elements, getting the values of each then doing what it is you want to do with the data.

That will take a bit of time to develop, at least for me, but there are a lot of examples on the Internet. There is another recent thread that I assisted on that did just that.

daniweb thread: http://www.daniweb.com/web-development/php/threads/468203/checkboxespassing-form-data-using-html-and-php and here is the demo for that one: http://itg.somee.com/dw/dw-468203/

Sample code for you to look/work with:

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery.js"></script>
</head>
<body>
<button id="addRowBtn">Add Row</button>
<form action="index.php" method="post" id="theForm">
<table id="tbl1">
<tr id="#header"><th>Week ending</th><th>Total week hours worked</th><th>Week overtime available</th><th>Total overtime</th><th>Comments</th></tr>
<tr class="editable"><td class="editableField"><input type="text" class="date" placeholder="Date" name="the_date[]"></td><td class="editableField"> <input type="text" class="hoursWorked" id="hrs-1" placeholder="Hours worked" name="the_hours_worked[]" onblur="compute(this)"></td><td class="overtimeAvailable"><input type="text" disabled class="overtimeInput" id="ovt-1" name="the_overtime[]"></td><td class="totalOvertime"><input type="text" disabled class="totalOvertimeInput" id="tot-1" name="totalOvertime[]"></td><td class="editableField"><textarea type="text" class="comments" placeholder="Insert comment" name="the_comments[]"></textarea></td></tr>
</table>
<input type="submit" text="Submit" id="submission" >
</form>
<script>

    var x = 0;
    var numRows = 1;
    function compute(obj) {
        var n = obj.id.toString().substring(4);
        x = Number(obj.value);
        document.getElementById('ovt-' + n).value = Number(x - 37.5).toFixed(2);

        // ? not sure what you are doing about total overtime.
        document.getElementById('tot-' + n).value = Number(x - 37.5).toFixed(2);
    }


$('#addRowBtn').click(function() {         
    $("#tbl1").append('<tr class="editable"><td class="editableField"><input type="text" class="date" placeholder="Date" name="the_date[]"></td><td class="editableField"><input type="text" class="hoursWorked" id="hrs-' + numRows + '" placeholder="Hours worked" name="the_hours_worked[]" onblur="compute(this)"></td><td class="overtimeAvailable"><input type="text" disabled class="overtimeInput" id="ovt-' + numRows + '" name="the_overtime[]"></td><td class="totalOvertime"><input type="text" disabled class="totalOvertimeInput" id="tot-' + numRows + '" name="totalOvertime[]"></td><td class="editableField"><textarea type="text" class="comments" placeholder="Insert comment" name="the_comments[]"></textarea></td><tr>'); 
  numRows++;
  });


</script>
</body>
</html>

I hope this is what you were looking for.

Hi JorgeM, thanks for all the info and your patience :-)!
OK, I guess one of the mistakes I was doind was to try to add another row on submit. Assuming I am posting to the same page, I take that if I add a row and then submit the form even if the added rows disappear they are still there somewhere?
thanks

I take that if I add a row and then submit the form even if the added rows disappear

Yes, it's gone. When you do stuff client side, the web server is unaware so if you post back, when the new page is created, the browser displays what ever the sever sent back to it. There is no state maintained. You have to take care of sending data back and forth.

With the example I provided above, yes you create additional HTML on the fly and when the form is submitted, you can send the input values back to the server. On the server (PHP) you have to figure out what is included on the POST data. You process it and send back HTML to the browser. To maintain the same number of rows or show the same data back to the user, on the server side, you would just generate the appropriate HTML. So what you can do there is add an additional input element in your form of type hidden. Client side, when you add a row, keep a running count (which we do in the example above numRows). Store this value in the input element. After the post, server side, get this value so when you are generating rows, you can do it will a loop and generate the number of rows based on this value. In the link above that I gave you, the example/demo shows you how to create rows in a table PHP side using a loop.

Fab, thanks for all your help!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.