How can I add more textboxs to page with php? - php

So I have this snippet of code that i want to insert into my site.
<table border="1">
<col width="130">
<col width="80">
<tr>
<td align = "right">Steps:</td><td align="center">Add as many steps as you need</td>
</tr>
<tr>
<td align = "right">Step 1:</td> <td><textarea style="width: 300px" class="form-control" name="steps[]" rows="3"></textarea></td>
</tr>
<tr>
<td align = "right">Step 2:</td> <td><textarea style="width: 300px" class="form-control" name="steps[]" rows="3"></textarea></td>
</tr>
<!--<tr>
<td align = "right">Step 3:</td> <td><textarea style="width: 300px" class="form-control" name="steps[]" rows="3"></textarea></td>
</tr>
<tr>
<td align = "right">Step 4:</td> <td><textarea style="width: 300px" class="form-control" name="steps[]" rows="3"></textarea></td>
</tr>
-->
</table>
For the most part, I have some commented out since I am testing to make sure that my site can handle multiple text boxs but the problem that I have is how can I insert steps into my site using php? I have these all on .php files in case you are wondering but I would like to insert more boxes with a button that is just under the current boxes. Every time the user clicks it, it should insert another box underneath the current boxes and update the number accordingly. I just am not sure where to start and how to get them in. Any ideas?

You would create new elements in JS and jQuery using the following code:
HTML
<button id="addButton">Add me!</button>
JS
var stepCounter = 3; //Number of the first step to be added
$('#addButton').click(function () {
var tr = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
var textarea = document.createElement("textarea");
$(textarea).attr("name", "steps[]");
$(td1).innerHTML("Step " + stepCounter);
stepCounter++;
$(tr).append(td1);
$(tr).append(td2);
$(td2).append(textarea);
$('#giveTheColAnId').append(tr);
});
Remember to include jQuery for this solution
Note that this code might not be perfect, but it should give you a very good start.

You can add these new Boxes with JavaScript/JQuery, if you dont want to reload the page after adding a new box. I would really recommend to have a look at this, instead of trying to do it with PH.
If you really want to do it just with php, you have to have a submit-button in a form
so add something like
<form method="post" action="?">
<input type="submit" name="submit" value="add row">
</form>
Now the PHP-part:
if(isset($_POST['submit'])) {
echo " [your usual tr-td-structure] ";
}
Keep in mind, that after reloading the page, a variable will lose its value.
So if you want to count up, you have to do it with javascript (or determine somehow which Step is the current and insert it in the echo). Of course set the last step in a hidden field inside the form (or append it as a get-param).

Can you use Jquery, Can't you do something like this ?
$(document).ready(function(){
$('#myButton').click(function(){
$(':input').append('<input type="textbox">');
});
});

Related

jQuery .next() when in a table

Trying to do some calc work with a dynamic table.
I have a table which uses a PHP for loop to create 2 rows with text inputs for the amount of days in the month.
I then need to take the first text input, and multiply it by 0.25 and show the result in the text input next to it.
Everything works, but cant get it to select the next text input.
This is the current:
$(".miles-input").on('keyup', function(){
var fuel_cost = $('.fuel_cost').val();
fuel_cost = parseFloat(fuel_cost);
var miles = $(this).val();
$('.price').val('£' +miles*fuel_cost);
});
The table when created created looks like:
<td><input type="text" class="miles-input"></td>
<td><input type="text" class="price"></td>
What I currently have changes all of the price inputs (of course) but no matter what I try I cannot get only the next input to change.
I have tried:
miles.next('.price').val('£' +miles*fuel_cost);
miles.closest('.price').val('£' +miles*fuel_cost);
Heres a jsFiddle:
http://jsfiddle.net/cd7t3ohn/
etc but none work. What is the correct way?
You can use:
$(this).parents("tr:first").find(".price:first").val('£' + (miles*fuel_cost));
It is not the best answer, but it will work. It will get you at the parent tr and then finding the first .price class.
miles is a String. Use this as your reference instead
$(this).next('.price').val('£' +miles*fuel_cost);
Try this:
$(function () {
$(".miles-input").on('keyup', function () {
var fuel_cost = $('.fuel_cost').val();
fuel_cost = parseFloat(fuel_cost);
var miles = $(this).val();
$(this).closest("tr").find(".price").val('£' + miles * fuel_cost);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
Fuel cost:
<input type='text' class='fuel_cost' value='0.25'>
<br>
<br>
<table style="width:500px">
<tr>
<td>Date</td>
<td>Miles</td>
<td>Cost</td>
</tr>
<tr class="input">
<td>1 / 2 / 2015</td>
<td>
<input type='text' class='miles-input' />
</td>
<td>
<input type='text' class='price' />
</td>
</tr>
<tr>
<td>1 / 2 / 2015</td>
<td>
<input type='text' class='miles-input'/>
</td>
<td>
<input type='text' class='price'/>
</td>
</tr>
</table>
my 5 cents
$(this).parent() // get <tr>
.next() // next row
.children('.price') // <td> with price
.etc...

PHP calculator results in a new page? PHP first attempt

I'm trying to get the website to send the calculation results to another page. The code below is working but I have no idea how to get the rows with the results to be shown in a new page.
I know that i have to change the action below to /mynewpage
But I just want the results not the whole table.
I have no idea what to do to the code to make it show the results only in a new page. IF everything statys in the same page the calculator works well.
It's my first attempt with PHP, I clearly have no idea of what I'm doing. Many thanks in advance.
<?php
if (isset($_POST['valuea'])) $valuea = $_POST['valuea'];
if (isset($_POST['valueb'])) $valueb = $_POST['valueb'];
if (isset($_POST['valuec'])) $valuec = $_POST['valuec'];
if (isset($_POST['valued'])) $valued = $_POST['valued'];
if (isset($_POST['valuee'])) $valuee = $_POST['valuee'];
$balance = $valuec * $valuee;
$newphone = $valuea;
$total = $balance + $valuea;
$total2 = $balance + $valueb;
echo <<<_END
<form method='post' action='/'>
<table border='0' width='500px' cellpadding='3' cellspacing='1' class="table">
<tr class="calcheading"><td colspan="2"><strong>CALCULATOR</strong></td></tr>
<tr class="calcrow"><td>Phone Value:</td><td align="center"><input type='text' name='valuea' value="$valuea"/></td></tr>
<tr class="calcrow"><td>Phone upfront cost:</td><td align="center"><input type='text' name='valueb' value="$valueb"/></td></tr>
<tr class="calcrow"><td>Monthly contract cost:</td><td align="center"><input type='text' name='valuec' value="$valuec"/></td></tr>
<tr class="calcrow"><td>Contract duration:</td><td align="center"><input type='text' name='valued' value="$valued"/></td></tr>
<tr class="calcrow"><td>No. months left in the contract:</td><td align="center"><input type='text' name='valuee' value="$valuee"/></td></tr>
<tr class="submit"><td colspan="2"><input type='submit' value='Calculate'/></td></tr>
_END;
?>
<tr class="calcheading"><td colspan="2"><strong>OPTION 1 - PAY REMAINING OF THE CONTRACT AND BUY SAME PHONE UNLOCKED</strong></td></tr>
<tr class="calcrow">
<td><i>Payment left to network:</td>
<td align="center"><input type="text" value="<?php echo round($balance)?>"></td></i>
</tr>
<tr class="calcrow">
<td><i>New unlocked phone:</td>
<td align="center"><input type="text" value="<?php echo round($newphone)?>"></td></i>
</tr>
<tr class="calcrow">
<td><i>TOTAL:</td>
<td align="center"><input type="text" value="<?php echo round($total)?>"></td></i>
</tr>
<br>
<tr class="calcheading"><td colspan="2"><strong>OPTION 2 - PAY BALANCE LEFT AND GET SAME PHONE ON A NEW CONTRACT*</strong></td></tr>
<tr class="calcrow">
<td><i>Payment left to network:</td>
<td align="center"><input type="text" value="<?php echo round($balance)?>"></td></i>
</tr>
<tr class="calcrow">
<td><i>New contract phone initial cost:</td>
<td align="center"><input type="text" value="<?php echo round($valueb)?>"></td></i>
</tr>
<tr class="calcrow">
<td><i>TOTAL:</td>
<td align="center"><input type="text" value="<?php echo round($total2)?>"></td></i>
</tr></table>
</form>
You can either send the values in a form and receive them on the other page using
$value1 = $_GET['value1'];
$value2 = $_GET['value2']; // etc
The other method would be saving them in a session variable, at the top of any pages where you wish to use session variables, call session_start(), then save them
$_SESSION['value1'] = $value1;
Then in another page, you can call them by simply
echo $_SESSION['value1'];
I'm not sure what you mean by new page? If you have a script like process.php that has that code then you can add session_start(); as your first line after the php start tag. By using $_Session['result']=$calc_result; on the 'process.php' you will store the value in your session. In the 'new page' script you call session_start(); again and you can get the stored value by saying $_Session['result'].
There are many ways to print your answers on a new page but lets keep it simple: A good way to do it would be for you to separate out the HTML form that posts the values and the php calculation logic on two different pages. So for example, your HTML form is in one file values.php (does not have any php code, you can name it with a .html prefix as well) and the php code is in another file calc.php. Now, to your form, specify an action such as
<form method='post' action='calc.php'>
This will post all the values to calc.php where your calculation code is and you can display the results however you please (not limited to a form again) but in a table or so on. Once you learn ajax, you'll never want to come back to doing this.
Here is a working barebones example: http://runnable.com/VEKvtTTrkXFwjAwL/calculator555-for-php

Best practice in adding form row

I have a working form with a javascript 'Add Row' button, data collection and processing by PHP. While it works, the code seems fairly high-maintenance and clumsy to me (for one thing, every time I change the form I need to work the same changes into the js that adds the new row). I'm looking for suggestions to make it more sleek and simple. Currently I'm assigning each input a unique name, with hidden input that keeps track of the number of rows for me, and then I use that number to determine the amount of for loops the PHP script needs to work through to post to the database.
One thing I've considered is changing from input names to using name[], but I'm not sure if that's the right method for my needs, and how I post each row as a separate record to the database. In any case, here's the code.
HTML
<table id="table1">
<tr style="display: none"><td colspan="2">
<input type="hidden" id="samp_count" name="samp_counter" value="" />
<input type="hidden" value="sample" name="type1" /></td>
</tr>
<tr>
<td >pic caption </td>
<td>
<input type="text" name="desc1"/></td></tr>
<tr>
<td >extended description</td>
<td><textarea style="width:100%" rows="7" name="notes1"></textarea></td>
</tr>
<tr>
<td>pic file</td>
<td><input id="pic_file1" type="file" name="pic1" /></td>
</tr>
</table>
<button type="button" class="add_row" width="40px" id="samp_add_button">add row
JavaScript for the button
$(document).ready(function(){
$("#samp_count").val("1");
$("#samp_add_button").click(function(){
var iter_str=$("#samp_count").val();
var pic_id = "#pic_file" + iter_str;
if (!$(pic_id).val()){
$("#samp_error").css("visibility","visible");
}
else{
iter_str ++; // update counter
$("#samp_count").val(iter_str); //reset counter in table header to current count
var a = '<tr><td colspan="2" ><span>pic caption<input type="text" name="desc'+iter_str+'"/></span><br /></td>";
var b = '<td rowspan="3">extended description<br /><textarea style="width:100%" rows="7" name="notes'+iter_str+'"></textarea></td>';
var c = '<tr><td colspan="2" >pic file</td><td><input id="pic_file'+iter_str+'" type="file" name="pic'+iter_str+'" /></td></tr>';
$("#table1").append(a+b+c);
$("#samp_error").css("visibility","hidden");
}
});
});
PHP
<?php
if(isset($_POST['send_button'])&&$isValid==TRUE){
$user = $_POST['user'];
$count_str1 = $_POST['samp_counter'];
$count1 = intval($count_str1);
for ($i=1; $i <= $count1; $i++) {
$desc= "desc".$i;
$pic= "pic".$i;
$notes= "notes".$i;
$desc_con = $_POST[$desc];
$notes_con = $_POST[$notes];
if($_FILES[$pic]["name"]){
if( formFileUpload($pic, $user)){ //custom function to validate and upload pics-- not relevant to question at hand
$uid_path = "portfolios/".$user."/";
$file_path=$uid_path.$_FILES[$pic]["name"];
$dbh = new PDO('mysql:host=localhost;dbname=db', 'admin','pass');
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);
$statement=$dbh->prepare("INSERT INTO portfolios (UserID, Description, FilePath, FileType, Notes) VALUES (?,?,?,?,?)");
$statement->bindParam(1,$user);
$statement->bindParam(2,$desc_con);
$statement->bindParam(3,$file_path);
$statement->bindParam(4,$_POST[type1]);
$statement->bindParam(5,$notes_con);
$statement->execute();
}
else{
$fileErrorDis="inline";
$isValid=FALSE;
} }}
?>
Link to working website -- self-explanatory but text in Hebrew (in some of the forms, the js has not been updated and the new row does not resemble the original one)

Using jQuery, I am submitting a form wihout refreshing the browser and I need help in listing the submitted data in a custom table column

I have a table where it's rows are generated by a foreach loop.
Each table row has two columns, one with a form and the other with the forms submitted data, which I have called notes. (and updates using a jQuery library without refreshing the browser).
<script>
$(".notes_column").each(function(){
var $myform = $(this).find('.notes_form');
var $mynotes = $(this).find('.notes');
$myform.validate({
submitHandler: function(form) {
$.post('process.php', $myform.serialize(), function(data) {
$mynotes.html(data);
});
}
});
}); // each function
</script>
<table id="myTable" class="tablesorter" border="1" cellpadding="5">
<thead>
<tr>
<th>Notes</th>
<th>Submit Note</th>
</tr>
</thead>
<tbody>
<?php
foreach($myarray as $myvar){
echo '
<tr>
<td>ID LIKE TO PLACE THE content of the div class="notes" HERE, HOW CAN I DO IT?</td>
<td class="notes_column">
<form class="notes_form" action="" method="post">
<input class="q" type="text" name="notes" size="30" placeholder="Place your notes here..." />
<input class="searchsubmit" type="submit" name="submit" value="Submit" />
</form>
<div class="notes"></div>
</td>
</tr>
';
}
?>
</tbody>
</table>
Right now I use a jQuery each function which iterates through each table column, and for each column with the class name ".notes_column" populates a div with the class "notes" with the submitted data.
The question is listed inside the code with capitalized letters, how can I populate the other column with the forms submitted data?
Any ideas?
Ty
I would create a <div> in the first <td> such as
<td>
<div class="put_notes_here">ID LIKE TO PLACE THE content of the div class="notes" HERE, HOW CAN I DO IT?</div>
</td>
Then populate it the same as you did before
$mynotes.closest("tr").find(".put_notes_here").html(data);
Change the selector for your each to $('#myTable tr'), then you can iterate through each in your table.
Then you could either do an each on the tr object to access each td, or make use of jQuery's :first-child and nth-child(2) etc in a subsequent selector

light box to show content according to what I have pressed

My problem has to do with PHP, jQuery and CSS.
I want to make a lightbox in a while loop, and then have the lightbox give me info for each of the rows.
There is a problem because it makes lightboxes for each of the rows, and with position:absolute we can see only the last row from the result. I don't want to see the last but I want the light box to show me info depending on which row I have clicked.
Here is the code:
jQuery:
$(document).ready(function(){
$('.lightbox').click(function(){
$('.boxi').css('display','block');
});
});
PHP:
$result = $db->query("SELECT * FROM destinations WHERE direction=1;");
while ($rows = mysql_fetch_array($result)) {
$name = $rows['name'];
$table .= '<div class="destionations">
<div class="name">Prej: <strong>'.$name.'</strong></div>
<table width="100%" class="extra" cellspacing="1" cellpadding="5" border="0" >
<tr class="bgC3" style="font-weight:bold">
<td width="20"></td>
<td>Deri</td>
<td width="50">Çmimi</td>
'.managment::cmimet_e_caktuara($name).'
</tr>
</table>
<div class="buttoni">
test
<div class="boxi">'.$name.'</div>
<form action="" method="POST">
<input type="text" name="new_city">
<input type="hidden" name="prej" value="'.$name.'">
<input type="submit" name="new_dest" value="Shto destinacionin">
</form>
</div>
</div>';
}
}
It looks like you're wanting to turn a div into a lightbox? You could just try adjusting your current CSS on .boxi to display: none; and set a z-index on it before - then adjust your javascript to something like this:
$('.lightbox').click(function(){
$('.boxi').show();
return false;
});
You could get much more complex with grabbing the next lightobx container when .lightbox is clicked - I'd recommend checking out the plugin Fancybox at fancybox.net, that's the one I typically use. Good luck!
$(document).ready(function(){
$('.lightbox').click(function(){
$('.boxi').css('display','block');
$('.boxi').css('z-index','999999');
});
});
I tried this because I thought that it will give higher z-index to the selected block but no its really primitive and wont ever work.
I am really too far from jQuery!

Categories