jQuery dynamic table with select - php

I'm trying to create a dynamic table, in other words, a table where the number of columns per row
isn't necessarily the same as the other rows
can be changed live by the user
in every added column, there is contained a dropdown box which is filled using a database request.
I would like to be able to fill this dropdown once when the page loads, and not every time a column is added(it's for a calendar, so worst case: multiple times per row = 31*x).
I'm using jquery 1.9 and php 5.3 for my programming.
I've tried with JSON and $.post(), but this escapes too much of the needed slashes and quotes, and due to my version 5.3 of php, I can't use the "DO_NOT_ESCAPE_ANYTHING" constants provided in php 5.4+ (and yes, I know that that name isn't right, it's by heart)
So, heart of the question:
How do I use a combination of jquery and php to put a HTML -tag in a javascript variable to output on a jquery-handled button-click.
jsfiddle: http://jsfiddle.net/pjc3y/3/
code:
HTML:
<form name="myform" id="myForm" action="#test">
<div>
<table id="persCalTable">
<tr id="DAY_0">
<td>
<input type="text" name="name" size="25" value="Enter your name here!" />
</td>
<td>
<button id="eventAdder">add event</button>
</td>
</tr>
</table>
<input type="submit" value="Submit" id="submitter" />
</div>
</form>
javascript:
function addCellToRow(row, cell) {
row.append(cell);
}
function expandCalendarTable(myObj) {
var DATA = myObj.closest('tr').attr('id').slice(4); //data is the number after DAY_
var selector = '#persCalTable #DAY_' + DATA; //selector is the table and the clicked row id
var cellHiddenField = '<input type="hidden" name="status" value="New" />';
var cellOtherData = "INSERT SELECT TAG HERE";
var cell = cellHiddenField + cellOtherData;
addCellToRow($(selector), cell); // add the cell to the row defined by the selector
eve.preventDefault(); // stop the page refresh(if not in a form, this is not needed, when in a form, this is needed)
//alert('Picked: ' + DATA);
}
$(document).ready(function () {
$("#submitter").click(
function (e) {
e.preventDefault();
alert($('#myForm').serialize());
});
$("[id^=eventAdder]").click(
function (e) {
e.preventDefault();
expandCalendarTable($(this));
});
});

While you can have differing columns per row in an HTML table, if you have the following:
<table>
<tr>
<td>Col 1</td>
<td>Col 2</td>
<td>Col 3</td>
</tr>
<tr>
<td>Col 1</td>
<td>Col 2</td>
</tr>
</table>
What you will end up with is a table with 3 columns, and in the second row the third cell will be empty and borderless. What you can do is use a seperate table for each row, set the widths as equal and calculate and set cell widths manually with jQuery.
As for the calendar. I would suggest you use JQueryUi, which has a great calender control or a similar library than going for a select. Either way, you can prepare the object ahead of time and store it in a variable. You will then have to use clone on it otherwise it will move to the last place you inserted it at.
$(function(){
// Prepare the select (obviously yours would be more complicated)
var select = $("<select>");
<?php for( $i = 0; $i < count($optionValue); $i++ ) { ?>
select.append($("<option value='<?php echo $optionValue[$i]?>'><?php echo $optionText[$i]?></option>"));
<?php } ?>
// Insert into relevant parts
$("#insert1").append(select.clone());
$("#insert1 select").attr("name", "select1");
$("#insert2").append(select.clone());
$("#insert2 select").attr("name", "select2");
})

Related

Get <select> value in $(this) row

I have a table consisting of elements like this
<tr>
<td>1</td>
<td><select>
<option>a</option>
<option>b</option>
</select>
</td>
<td>3</td>
<button id="button"></button>
</tr>
How can i get all values of current row including selected option when press button by using jquery?
I want to get: 1 'a'('a' option selected for example) 3
If by "values" you mean the 1 and the 3 in the other two cells, you'd use closest to find the row, then use find or children to access the tds in it. Here's one way you might do it:
$("#button").on("click", function() {
// Get the row
var row = $(this).closest("tr");
// Get the cells and their contents:
row.children("td").each(function() {
var $this = $(this);
// Ignore the one with the button
if (!$this.find("button").length) {
// Does this one have the select?
var select = $this.find("select");
if (select.length) {
// Yes, use that
console.log(select.val());
} else {
// No, grab text
console.log($(this).text());
}
}
});
});
<table>
<tbody>
<tr>
<td>1</td>
<td><select>
<option>a</option>
<option>b</option>
</select>
</td>
<td>3</td>
<td>
<button id="button">I'm a button</button>
</td>
</tr>
</tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
But refer to the API, there are lots of other ways you might access those tds.
Note that I wrapped the button in a td. Your original markup is invalid, you can't have a button as a direct child of a tr.
Also note that if you have more than one tr, you can't use id="button" on all of them (probably better to use a class), but I'm guessing from the ID that that's just a placeholder you put in for the question. :-)

Accessing data in an html table with jQuery using a onClick event handler

I have a table that is being populated by a foreach loop to get data from a database:
foreach ($retrieve_data as $retrieved_data) {
$content .= "
<tr id=\"id_$retrieved_data->id\">
<td> $retrieved_data->id </td>
<td> $retrieved_data->posname </td>
<td> $retrieved_data->month </td>
<td> $retrieved_data->year </td>
<td> $retrieved_data->availableinv </td>
<td> $retrieved_data->maxinv </td>
<td> <button type=\"button\" id=\"editImpressionsBtn\" value=\"Edit\">Edit </button>
</tr>";
}
I want to write a jQuery function that gets data from the table like the id, availableinv, and maxinv when the edit button is clicked.
jQuery(document).on('click', 'editImpressionsBtn', function() {}
How can I assign a variable in this function to the data in each of these columns for only the row that the edit button was clicked?
Something like this? One thing I noticed, you need to make sure to add the selector (. or # for class or ID) to the handler.
$('.table_selector tbody').on('click', '.editImpressionsBtn', function(){
row = $(this).closest('tr');
})
Then you can add values or ids and get them like this
var my_id_value = row.attr('id')
Target the TR and then the different TD's
$('#editImpressionsBtn').on('click', function() {
var tr = $(this).closest('tr');
var tds = tr.find('td');
var id = tds.eq(0).text();
var avb = tds.eq(4).text();
});
If you're generating more than one table on the serverside, make sure you don't use the same ID for all of them, use a class instead.
There are three parts to this answer. Two are core to your question, one is a coding option / improvement:
First:
As your table is being built in a loop, I presume you've got multiple rows. Be aware that you can not have multiple buttons with the same ID. This is not only semantically incorrect, it will cause issues with jQuery. So, change the id of the button to be a class instead:
<button type="button" class="editImpressionsBtn" value="Edit">Edit </button>
Second:
Now, in your jQuery, you can access that row fairly easily:
jQuery(document).on('click', 'button.editImpressionsBtn', function() {
var row = $(this).closest('tr');
var id = row.find('td:eq(0)').text();
var posname = row.find('td:eq(1)').text();
// ... etc
});
Third:
Escaping quotes inside of quotes like you are doing is a pain to code, and more difficult to maintain and read. I'd recommend in this case using a HEREDOC.
Example:
$content .= <<<HTML
<tr id="id_$retrieved_data->id">
<td> $retrieved_data->id </td>
<td> $retrieved_data->posname </td>
<td> $retrieved_data->month </td>
<td> $retrieved_data->year </td>
<td> $retrieved_data->availableinv </td>
<td> $retrieved_data->maxinv </td>
<td> <button type="button" class="editImpressionsBtn" value="Edit">Edit </button>
</tr>
HTML;

How to generate a json array from a table data inside a <td> tag

I am trying to get those data in the JSON format. Would you please help me to generate that? Please help I am not very familiar with jquery and php.
html code looks like this
<form>
<table>
<tr>
<td>//some code for other table elements</td><tr>
<tr>
<td>Critical Times (Coverage): </td>
<td rowspan="3" colspan="2">
<div>
<table width="100%" bgcolor="white" border="0px" name="criticalTime" id="criticalTime">
</table>
</div>
</td>
<td>
<input type="button" id="timeAdd" value="+"/><br>
<input type="button" id="timeRemove" value="-"/>
</td>
</tr>
<tr>
<td>//some code for other table elements</td>
</tr>
</table>
</form>
my .js file has the following to handle the addition of rows to the table when click the + button.
var rowCountr = 0;
var timeTable="<thead><tr bgcolor='E1ECFF'><th></th><th align='left'>Start Time</th><th align='left'>End Time</th></tr></thead>";
/* insert the html string*/
$("#criticalTime").html( timeTable );
/*Event for the +(Add) button in critical time table*/
var timeRwcntr=0;
timeRow="<tr><td><input type='checkbox' id='row'</td><td><input type='text' id='start' /></td><td><input type='text' id='end'/></td></tr>";
$('#timeAdd').click(function(){
$('#criticalTime').append(timeRow);
rowCountr++;
timeRwcntr++;
});
$('#timeRemove').click(function(){
$('#criticalTime tr:last-child').remove();
});
When I click the submit button from main form I need to get those values entered in the input fields and generate an JSON array to store those in database. Please help.
For this problem, I think that JSON may be overkill. You're just trying to send your table's input fields back to the server on a postback right? When you create your table rows, add a uniquely identifying number in the "name" attribute of your form controls <input name="'.$id.'_field" /> for example if you are rendering the table server-side; the code would be similar for javascript. Then, when you post back, you can loop through each row by counting and then access the POST variable you got back by referencing the name. Example:
for ($i = 0; $i < $rowcount; $i++) {
$field_value = $_POST[$i.'_field'];
...
}
JSON is great for more complex data sets, but in your case it sounds like you have structured two-dimensional rows and columns.

Access an html table data in PHP

If I have a table like this in an html form,
<form method="POST" action="a.php">
<table name="dataTable">
<tr>
<td>row one col one</td>
<td>row one col two</td>
<td>row one col three</td>
</tr>
<tr>
<td>row two col one</td>
<td>row two col one</td>
<td>row two col one</td>
</tr>
</table>
</form>
how can I access the table data when the form is submitted to p.php?
$dataList = $_POST['dataTable']; ???????
A straightforward work-around would be to add hidden fields to all your cells:
<form method="POST" action="a.php">
<table name="dataTable">
<tr>
<td>row one col one<input type="hidden" name="row_one_cell_one" value="row one col one" /></td>
<td>row one col two<input type="hidden" name="row_one_cell_two" value="row one col two" /></td>
etc...
It leaves your view unchanged, but you can acces the cells in your php script with this simple code:
$cellData = $_POST['row_one_cell_one'];
without any workarounds and conversions, you can't.
What you can do is converting your table in a serialized array with JavaScript before submitting and setting the result in a hidden input. Then you can read the value in PHP and de-serialize the array, getting all the values. If you do it right, you can even iterate over the rows and columns.
You can make use on JavaScript to render the table DOM,
and set it to a hidden field right before you do the submission,
so, PHP able to interpret is part of the $_POST
<form method="post" onSubmit="set_value()">
<table name="dataTable">
...
</table>
<input type="hidden" value="" id="hidden_table" name="hidden_table" />
</form>
<script>
function set_value()
{
var obj = document.getElementById("hidden_table");
var tbl = document.getElementsByName("dataTable")[1]
obj.value = tbl.innerHTML;
}
</script>
However, when using JavaScript DOM, it will return full specification of TABLE elements
include THEAD, TBODY ... etc
First link using the topic as keywords in google shows up this: http://wonshik.com/snippet/Convert-HTML-Table-into-a-PHP-Array
I'm sure you can adapt it to your problem.

Put specific tds from a table row into edit using jQuery (then update w/ ajax)

I'm somewhat new to jQuery, so I could use some help here.
This is my issue:
I have a PHP script outputting a dynamic table. Each row has an "edit" button, plus some other fields. Only 3 of those need to be turned into an input box. The edit button should only put that specific row into "edit mode." I got as far as assigning each row a unique class by adding a number to the end of it.
I have been able to use jQuery to change all of the rows into edit mode, but I need it to be specific to a row.
An example row would have classes like name0, price0, and desc0. The next row would go on to classes name1, price1, and desc1 (for the fields that need changed). How can I reference these values and pass them to jQuery so it processes an event on just those elements?
There are two ways of doing this:
Dynamically creating the elements when the button is pressed; or
Hiding and showing elements that already exist.
Too much DOM manipulation can be really slow (particularly on certain browsers) so I favour (2). So for example:
<table class="editable">
<tbody>
<tr>
<td>one</td>
<td>
<div class="view">two</div>
<div class="edit"><input type="text"></div>
</td>
<td>
<div class="view">three</div>
<div class="edit"><input type="text"></div>
</td>
<td>
<input type="button" class="edit" value="Edit">
<input type="button" class="send" value="Send" disabled>
<input type="button" class="cancel" value="Cancel" disabled>
</td>
</tr>
</tbody>
</table>
with:
table.editable div.edit { display: none; }
and
$(function() {
$(":button.edit").click(function() {
var row = $(this).closest("tr");
row.find("input.view").attr("disabled", true");
row.find("div.view").each(function() {
// seed input's value
$(this).next("div.edit").children("input").val($(this).text());
}).fadeOut(function() { // fade out view
row.find("div.edit").fadeIn(function() { // fade in edit
row.find("input.edit").removeAttr("disabled"); // enable edit controls
});
});
});
$(":button.cancel").click(function() {
var row = $(this).closest("tr");
row.find("input.edit").attr("disabled", true");
row.find("div.edit").fadeOut(function() {
row.find("div.view").fadeIn(function() {
row.find("input.view").removeAttr("disabled");
});
});
});
$(":button.save").click(function() {
// ...
});
});

Categories