I'm still new with yii
and now I want to add a Javascript code that can append dropdown list to the table, when I click the button.
Here is my table:
<table class="table table-hover" id="table-add-more">
<tr>
<th style="width:50px;">No</th>
<th style="width:200px;">Name</th>
<th style="width:50px;">Count</th>
<th style="width:30px;"></th>
</tr>
<tbody>
</tbody>
</table>
Here is my button:
<a id="btn-add-more" class="btn btn-sm btn-success">Add More</a>
Here is my script:
<script>
$(document).ready(function(){
var number = 1;
var product = <?php $product = Product::model(); echo $form->dropDownList($product,'ID', CHtml::listData(Product::model()->findAll(), 'ID', 'name')); ?>;
$('#btn-add-more').click(function() {
var more_field = "<tr>"+
"<td>"+number+"</td>"+
"<td>"+
<?php echo "product"; ?>
+"</td>"+
"<td><input type='number'/></td>"+
"<td><input type='checkbox'/></td>"+
"</tr>"
$('#table-add-more').append(more_field);
number = number + 1;
});
});
</script>
I got an error message:
"unexpected token <"
near the var product = <select name="Product[ID]" id="Product_ID">
but I can't found the mistake yet.
Please help..
I think the better way is to have dropdown list with display: none at initialization and when you click that button, you can change display to block. But If you want to append dropdown to your table, I think you have tow problem in your javascript function:
1.You need to wrap this php code into "".
var product = "<?php $product = Product::model(); echo $form->dropDownList($product,'ID', CHtml::listData(Product::model()->findAll(), 'ID', 'name')); ?>";
I think you need to have <?php echo $product; ?>, instead of <?php echo "product"; ?>
Related
I recently ran into a problem I wasn't quite sure how to solve. Sharing it here in case it helps someone else.
Use Case: User enters a string in a search box on a PHP page. On submit, the page queries the database and then posts results to a table on the same page. User then selects a single record with a radio button and needs to post only that record to a different PHP page. The second page does not have access to the database.
I took the actual page and created a sample page for clarity and testing, since the original had about 15 table columns.
<div class="container">
<div class="row" style="margin-top: 1rem;">
<div class="col-sm">
<form action="" method="post">
<table class="fit" id="entry">
<tr>
<td class="fit"><label for="start">Planet (try <strong>Caprica</strong> or <strong>Picon</strong>): </label></td>
</tr>
<tr>
<td class="fit"><input type="test" id="planet" name="planet" required autofocus /></td>
</tr>
</table>
<input class="btn btn-primary" type="submit" value="Get Characters" />
</form>
</div>
</div>
</div>
<div class="container" style="margin-top: 2rem;">
<div class="row">
<div class="col-sm">
<?php
require_once('./resources/pdo.php');
if ( isset($_POST['planet']) ) {
$planet = strtolower($_POST['planet']);
$pdo = new myPDO('phppostpost');
try {
$stmt = $pdo->prepare('CALL devCharacters(?)');
$stmt->bindParam(1, $planet, PDO::PARAM_STR);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
die("Error occurred: " . $e->getMessage());
}
?>
<div class="table-responsive">
<table class="table table-striped table-hover">
<thead class="thead-light">
<tr>
<th class="fit">Select</th>
<th class="fit" scope="col">Customer First</th>
<th class="fit" scope="col">Customer Last</th>
<th class="fit" scope="col">Planet</th>
</tr>
</thead>
<tbody>
<?php while ($r = $stmt->fetch()): ?>
<tr>
<?php echo "<td class='fit'><input type='radio' id='cust-" . $r['customer_id'] ."' name='cust-id' value='". $r['customer_id'] . "' </td>"; ?>
<?php echo "<td class='fit'>" . $r['first_name'] . "</td>"; ?>
<?php echo "<td class='fit'>" . $r['last_name'] . "</td>"; ?>
<?php echo "<td class='fit'>" . $r['origin_planet'] . "</td>"; ?>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
<input class="btn btn-primary" onclick="getSelectedRowData();" type="submit" value="Send" />
<?php } ?>
</div>
</div>
</div>
As a relatively new developer, I couldn't figure out how to (1) grab just the selected row and (2) post data on submit from just that row, rather than from the the original search form.
After much Googling, as well as a kick in the pants from a Stack Overflow user who reminded me I needed to actually research for more than 20 minutes (thank you!), I was able to solve it.
I'll post the answer below for anyone else who runs into a similar problem.
To solve this, I used JavaScript to grab the selected row. In order to efficiently grab the correct record, I updated each TD element to have a unique, dynamically-generated ID:
<?php echo "<td class='fit' id='fname-" . $r['customer_id'] ."'>" . $r['first_name'] . "</td>"; ?>
<?php echo "<td class='fit' id='lname-" . $r['customer_id'] ."'>" . $r['last_name'] . "</td>"; ?>
<?php echo "<td class='fit' id='planet-" . $r['customer_id'] ."'>" . $r['origin_planet'] . "</td>"; ?>
I also gave the table body an ID so I could grab it quickly without grabbing a parent, then children, etc.:
<tbody id="results-body">
Finally, here's the JavaScript.
function getSelectedRowData() {
const tableRowArray = Array.from([document.getElementById('results-body')][0].rows);
let custFirst;
let custLast;
let custPlanet;
tableRowArray.forEach((tableRow, i) => {
cellButton = tableRow.getElementsByTagName('input');
if (cellButton[0].checked == true ) {
const rowID = cellButton[0].id.split('-').pop();
custFirst = document.getElementById('fname-' + rowID).innerHTML;
custLast = document.getElementById('lname-' + rowID).innerHTML;
custPlanet = document.getElementById('planet-' + rowID).innerHTML;
}
});
/* Build a hidden form solution to prep for post.
Source: https://stackoverflow.com/questions/26133808/javascript-post-to-php-page */
let hiddenForm = document.createElement('form');
hiddenForm.setAttribute('method', 'post');
hiddenForm.setAttribute('action', 'newpage.php');
hiddenForm.setAttribute('target', 'view');
const fieldCustFirst = document.createElement('input');
const fieldCustLast = document.createElement('input');
const fieldCustPlanet = document.createElement('input');
fieldCustFirst.setAttribute('type', 'hidden');
fieldCustFirst.setAttribute('name', 'custFirst');
fieldCustFirst.setAttribute('value', custFirst);
fieldCustLast.setAttribute('type', 'hidden');
fieldCustLast.setAttribute('name', 'custLast');
fieldCustLast.setAttribute('value', custLast);
fieldCustPlanet.setAttribute('type', 'hidden');
fieldCustPlanet.setAttribute('name', 'custPlanet');
fieldCustPlanet.setAttribute('value', custPlanet);
hiddenForm.appendChild(fieldCustFirst);
hiddenForm.appendChild(fieldCustLast);
hiddenForm.appendChild(fieldCustPlanet);
document.body.appendChild(hiddenForm);
// Post
window.open('', 'view');
hiddenForm.submit();
}
This worked for me, but I'm sure there's a better way to do this. Hopefully this (1) helps someone else and (2) a better solution is posted!
Here's a working demo: https://postfrompost.paulmiller3000.com/
Full source here: https://github.com/paulmiller3000/post-selected-from-post
I've made a combobox based on the database.
I want when I've selected one combobox and instantly display the appropriate table combobox that I choose.
Example when I choose west java table will show bandung and bogor.
this my controller
public function show() {
$data['provinsi'] = $this->mdl_onchange->get_provinsi();
$data['kota'] = $this->mdl_onchange->get_kota();
$this->load->view('form_onchange', $data);
}
this my model
function get_provinsi() {
$query = $this->db->get('table_provinsi');
return $query->result();
}
function get_kota() {
$query = $this->db->get('table_kota');
return $query->result();
}
this is my view
<p>
<label for="select_provinsi"></label>
<select name="select_provinsi" id="select_provinsi">
<option>--Pilih Provinsi--</option>
<?php foreach($provinsi as $row_provinsi) { ?>
<option value="<?php echo $row_provinsi->id_provinsi?>">
<?php echo $row_provinsi->nama_provinsi; ?>
</option>
<?php } ?>
</select>
</p>
<table border="1" name="select_kota" id="select_kota" style="border-
collapse:collapse; width:60%;">
<tr style="background:yellow;">
<th>Id kota</th>
<th>Id provinsi</th>
<th>nama kota</th>
</tr>
<?php foreach($kota as $c){?>
<tr>
<td>
<?php echo $c->id_kota; ?>
</td>
<td>
<?php echo $c->id_provinsi; ?>
</td>
<td>
<?php echo $c->nama_kota; ?>
</td>
</tr>
<?php } ?>
</table>
my jquery
<script type ="text/javascript">
$("#select_kota").chained("#select_provinsi");
</script>
I've made like this but its data always appear when I have not chosen combobox western Java.
it is
I see you are using chained Jquery. That's for chaining two selects, not for a table.
For this, the best approach you could get is to perform an Ajax call to get the table rows and modify the table tbody inner HTML.
First, you need to modify the model get_kota() function, to select only the kota on a provinsi, by it's id_provinsi:
function get_kota($id_provinsi) {
$this->db->where('id_provinsi', $id_provinsi);
$query = $this->db->get('table_kota');
return $query->result();
}
After that, create a new function on your controller to return the new values via Ajax. Here I'll include also the modification to the original method to remove the first call for kotas:
public function show() {
$data['provinsi'] = $this->mdl_onchange->get_provinsi();
$this->load->view('form_onchange', $data);
}
public function ajax_getkotas($id_provinsi) {
$kotas = $this->mdl_onchange->get_kota($id_provinsi);
foreach ($kotas as $kota) {
echo '<tr>\n';
echo '<td>' . $kota->id_kota . '</td><td>' . $kota->id_provinsi . '</td><td>' . $kota->nama_kota . '</td>\n';
echo '</tr>\n';
}
}
Now, let's go back to your view. Let's divide it into three parts: the select, the table and the jquery.
You can keep your select as it is right now.
The table will be empty at first, you can maybe have something like this:
<table border="1" name="select_kota" id="select_kota" style="border-
collapse:collapse; width:60%;">
<thead>
<tr style="background:yellow;">
<th>Id kota</th>
<th>Id provinsi</th>
<th>nama kota</th>
</tr>
</thead>
<tbody>
<tr><td>Please, select a provinsi from the above dropdown to display results</td></tr>
</tbody>
</table>
And now let's go for the JQuery Ajax call:
$('#select_provinsi').on('change', function() {
$.ajax({
type: 'GET',
url: "<?php echo site_url('your_controllername/ajax_getkotas') ?>" + "/" + $('#select_provinsi').val() , // we call our new function with the selected id
dataType: "html",
success: function (data) { // change the data from our response
$('#select_kota tbody').html(data); //rows are printed inside the tbody of our table
},
failure: function(err) {console.log("Error on the Ajax call");} // Some error feedback just in case. You can check network XHR to see what's going on.
});
})
With this I think you can get it working. Let me now it that's works for you or we need to change anything.
I have a table which displays results from my DB. In the last column I have checkboxes and by clicking submit button I am sending an array of account_id's to another php file. Everything works fine but the problem is that I am using a Bootstrap responsive table which can show 10-100 results on each page and the form only captures results on the current page. If I check boxes on different pages and switch between them, they still remain checked, though.
Here is my HTML:
<form action="compare.php" method="post">
<table class="table table-hover" id="dataTables-example">
<thead>
<tr>
<th style="text-align:center;">Account name</th>
<th style="text-align:center;">Address</th>
<th style="text-align:center;">Phone number</th>
<th style="text-align:center;">Website</th>
<th style="text-align:center;">Compare</th>
</tr>
</thead>
<tbody>
<?php
$result= mysql_query("select * from accounts order by account_name ASC" ) or die (mysql_error());
while ($row= mysql_fetch_array ($result) ){
?>
<tr>
<td class='clickable-row' data-href="select.php?id=<?php echo $row ['account_id'];?>"> <?php echo $row ['account_name'];?></td>
<td class='clickable-row' data-href="select.php?id=<?php echo $row ['account_id'];?>"> <?php echo $row ['address']; ?></td>
<td class='clickable-row' data-href="select.php?id=<?php echo $row ['account_id'];?>"> <?php echo $row ['phone_number']; ?></td>
<td class='clickable-row' data-href="select.php?id=<?php echo $row ['account_id'];?>"> <?php echo $row ['website']; ?></td>
<td> <input type="checkbox" name="checkboxvar[]" value="<?php echo $row ['account_id'];?>" /></td>
</tr>
<?php } ?>
</tbody>
</table>
<input class="btn btn-success" type="submit" value="Compare" id="submit">
</form>
I tried to use jQuery to see if it can capture the checkboxes from the whole table, but results is the same as trying an HTML form.
This script is supposed to capture them and make an alert:
<button id="bt1">Get</button>
<script>
$('#bt1').on('click', function () {
//Get checked checkboxes
var checkedCheckboxes = $("#dataTables-example :checkbox:checked"),
arr = [];
//For each checkbox
for (var i = 0; i < checkedCheckboxes.length; i++) {
//Get checkbox
var checkbox = $(checkedCheckboxes[i]);
//Get checkbox value
var checkboxValue = checkbox.val();
//Get siblings
var siblings = checkbox.parent().siblings();
//Get values of siblings
var value1 = $(siblings[0]).text();
var value2 = $(siblings[1]).text();
arr.push(checkboxValue + '-' + value1 + '/' + value2);
alert(checkboxValue + '-' + value1 + '/' + value2);
}
});
</script>
Is there a way to do it?
You can use Datatables object:
$('input', oTable.fnGetNodes()).each(function () {
if($(this).is('checked')){
console.log($(this).val());
}
});
Solved!
Include this script:
<script type="text/javascript" src="//cdn.datatables.net/plug-ins/f2c75b7247b/api/fnGetHiddenNodes.js"></script>
And this paste this function:
<script>
$(document).ready(function() {
oTable = $('#yourTableID').dataTable();
$('form').submit(function(){
$(oTable.fnGetHiddenNodes()).find('input:checked').appendTo(this);
});
});
</script>
All checkboxes are captured by clicking submit button.
I am currently building an internal tool for viewing and editing SQL-like tables via the web. I have some PHP and html written that generates these tables and jQuery written that does this, so far:
Delete Rows
Add New Rows
Output form value after entry
The ultimate goal, of course, is to generate a SQL statement using INSERT, UPDATE, DELETE, etc on the modified data. I have a grasp on how to concatenate the results into such a statement, but could use help targeting columns for it.
My main concern is modifying the form value output function so that I can store any updated entries in an array and output them as a CSV string. I've read about .each, .map, .push, and .serializeArray. I'm not sure exactly how to use/combine these methods to accomplish the desired result. Here are some code snippets:
The current jQuery:
$('#add_row').on('click', function(){
$('<tr><td id="data"><input class ="new_row"></td><td id="data"><input class ="new_row"></td><td id="data" style="text-align:center;"><input class ="new_row"></td><td id = "Delete_Button"><button class="rmv_row">-</button></td></tr>').appendTo('#SQLdata');
});
$("table").on('keyup', 'input', function(){
$('#output').text($(this).val());
});
$('table').on('click', '.rmv_row', function(){
$(this).closest('tr').remove();
});
});
and the PHP/HTML:
<table id="SQLdata">
<tr style="background-color: margin-left:#6b685c;">
<td style="background-color: margin-left:#6b685c; font-family:tahoma,arial,verdana,sans-serif"; colspan="3">
<form style="color:black;" method="post" action="WebEventsStructureColumnTool.php">
Select your table name:
<select method="post" name="table_name" id="picker">
<option>Removed For Security</option>
</select>
<input type="submit" value="Go" name="submit">
</form>
</td>
<td><button id="add_row">Add a Row</button></td>
</tr>
$tableName = $_POST['table_name'];
$statementObject = $pdo->prepare("SELECT a, b, c FROM tab WHERE _id =?");
$statementObject->bindParam(1, $tableName, PDO::PARAM_STR);
$statementObject->execute();
$statementObject->bindColumn('a', $Col1);
$statementObject->bindColumn('b', $Col2);
$statementObject->bindColumn('c', $Col3);
while ($statementObject->fetchAll(PDO::FETCH_BOUND)){
// Gets an array from the CSVs in the column :
$Column1 = explode(",", $Col1);
$Column2 = explode(",", $Col2);
$Column3 = explode(",", $Col3);
}
//Fetches the total number of values from each exploded array:
$Count1 = count($Column1);
$Count2 = count($Column2);
$Count3 = count($Column3);
//Establishes the total length/height of the table:
$largest = $Count1;
if ($Count2 > $largest){
$largest = $Count2;
}
if ($Count3 > $largest){
$largest = $Count3;
}
echo '
<tr>
<th>a</th>
<th>b</th>
<th style="text-align: center">c</th>
<th>delete row</th>
</tr>';
for($i = 0; $i < $largest; $i++){
$tableRows[] =
"<tr>
<td id='data'>
<input type='text' value='" . $Column1[$i] . "'>
</td>" .
"<td id='data'>
<input type='text' value='" . $Column2[$i] . "'>
</td>" .
"<td id = 'data' style='text-align:center;'>
<input type='text' value='". $Column3[$i]. "'>
</td>
<td id = 'Delete_Button'><button class='rmv_row'>-</button></td>";
}
foreach ($tableRows as $row){
echo $row;
}
echo '</table><div><table><tr id="output" colspan="4"></tr></table>'
If anyone also has advice/recommendations on existing code, feel free to criticize. I am a young developer just starting out and could use all the help I can get. Thanks!
I added this bit this morning and am now successfully getting CSVs:
var string = new Array()
function updateString(){$('#output').text(string);}
$('input').each(function(){
string.push($(this).val());
});
Working on creating three different arrays for each data manipulation option and limiting printing to conditionals.
I have this PHP in my application,
<table><tr>
<?php
if($music_interests !== FALSE)
{
$count = 0;
foreach($music_interests as $interest)
{
?>
<td>
<div class="interest inline">
<img src="<?php echo $interest['image']; ?>" alt="<?php echo truncate($interest['name'], 25); ?>" class="interest_img"/>
<p><?php echo truncate($interest['name'], 25); ?></p>
<div class="interest_popup">
<img src="<?php echo $interest['image']; ?>" alt="<?php echo truncate($interest['name'], 25); ?>" class="interest_img left"/>
<div class="right">
<strong><?php echo truncate($interest['name'], 25); ?></strong>
<p>Music<br><?php echo #$interest['num_users']; ?> users have this interest.</p>
<?php echo anchor('my_profile/remove_interest/'.$interest['id'], 'Remove interest', array('class' => 'button red upper rounded_5 small remove')); ?>
</div>
<div class="clear"></div>
</div><!--.interest_popup-->
</div>
</td>
<?php
$count = ($count + 1)%4;
if ($count == 0)
{
echo "</tr><tr>";
}
}
}
?>
As you can see the PHP creates a table and every 4th <td> creates a new row. I am now adding ajax functionality to my app, but I cannot work out how I would work out if I need to create a new row first before appending a <td> that my ajax request has created.
Currently I have this code that adds a td to my table,
var interest = "<td>" + msg.name + "</td>";
self.parent().children('table').append(interest);
You shouldn't append table cells directly into the table. Table cells goes into table rows.
Get the last row in the table, and check how many cells there are in it. If there are four cells already you need to create a new table row and append to the table, then add the cell to that row. Otherwise you can add the cell to the existing row.
Warnign! untested code! I would do something like this:
var interest = "<td>" + msg.name + "</td>";
var $lastTr = self.parent().children('table tr:last');
if ($lastTr.find("td").size() < 4) {
$lastTr.append(interest);
} else {
interest = "<tr>" + interest + "</tr>";
self.parent().children('table').append(interest);
}
Update: I modified the answer since now I have better understanding of the question.
Here's a sample that shows how you can dynamically create td and tr elements. Replace the constant content ("some value") with whatever you get using AJAX.
JSFiddle (jQuery 1.7.1 added): http://jsfiddle.net/BUR7p/3/
<html>
<head>
<script language="javascript" type="text/javascript">
//my previous understanding of the question
//function AddNewRow()
//{
// var row = $(document.createElement("tr"));
// row.append("<td>some value</td>");
// row.append("<td>another val</td>");
// $("#mytable").children().append(row);
//}
//my corrected understanding: you don't know how
//to decide how to create a new row to put in the
//table. note i added a table body explicitly, it
//is added by default automatically if you don't.
function AddNewData()
{
var row = $("#tablebody").children().last();
if(row.children().length >= 4)
{
console.log("creating a new row...");
//create a new row if we need one
row = $(document.createElement("tr"));
$("#tablebody").append(row);
}
else console.log("using existing row...");
//add new datum to row
row.append("<td>some value</td>");
}
</script>
</head>
<body>
<p>
<table id="mytable">
<tbody id="tablebody">
<tr>
<td>one</td>
<td>two</td>
</tr>
<tr>
<td>three</td>
<td>four</td>
</tr>
</tbody>
</table>
</p>
Add new row
</body>
</html>
As an alternative, you can modified the server side in a way that returns, in addition to the data, a flag whether the data should be created in a new row or not.
Please follow up and tell us if this helps or not.
answer found at this question:
// pass stuff to insert to .after() as an HTML string
$('#myTable tr:last').after('<tr>...</tr><tr>...</tr>');
documentation for :last psuedoselector and .after() function