I am trying to make a "td" disappear whenever the date occured before that date today (in the past). But what is happening is that only the first column is affected while the others aren't.
<script type="text/javascript">
//<![CDATA[
function vanish() {
downloadUrl("bckendcommmap.php", function(data) {
var xml = data.responseXML;
var markers50 = xml.documentElement.getElementsByTagName("marker50");
// Split timestamp into [ Y, M, D, h, m, s ]
for (var i = 0; i < markers50.length; i++) {
var newdate = markers50[0].getAttribute("date");
var trainid = markers50[0].getAttribute("trainingid");
var t = newdate.split(/[- :]/);
// Apply each element to the Date function
var d = new Date(t[0], t[1]-1, t[2]);
alert(d);
var rightNow = new Date();
var trainingDate = new Date(d);
if (rightNow < d ) {
document.getElementById("assess").innerHTML = ""; /* make it disappear */
}
else if (rightNow > d ) {
document.getElementById("edit").innerHTML = "";
}
// -> Wed Jun 09 2010 13:12:01 GMT+0100 (GMT Daylight Time)
}
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
Here are parts of the table and the td:
<body onload="vanish();">
<table id="gradient-style" width="290" border="0" cellspacing="0" cellpadding="0" >
<thead>
<tr>
<td align="center"><strong> Training Name</strong></td>
<td align="center"><strong> Description</strong></td>
<td align="center"><strong> Location</strong></td>
<td align="center"><strong> Date</strong></td>
<td align="center"><strong> Time Start</strong></td>
<td align="center"><strong> Time End</strong></td>
<td align="center"><strong> Capacity</strong></td>
<td align="center" colspan="2"><strong>Actions</strong></td>
</tr>
</thead>
<?php
while($rows=mysql_fetch_array($get)){
?>
<tbody>
<tr>
<td><?php echo $rows['title']; ?></td>
<td><?php echo $rows['description']; ?></td>
<td><?php echo $rows['location']; ?></td>
<td><?php echo $rows['date']; ?></td>
<td><?php echo $rows['start']; ?></td>
<td><?php echo $rows['end']; ?></td>
<td><?php echo $rows['capacity']; ?></td>
**<td align="center"><div id="edit">Edit</div></td><td align="center"><div id="assess">Assess Training</div></td>**
</tr>
</tbody>
<?php
}
?>
</table>
</body>
This line is the td that I'm trying to vanish with respect to the date:
<td align="center"><div id="edit">Edit</div></td><td align="center"><div id="assess">Assess Training</div></td>
You are only hiding the div, if you want to hide td Try this:
**<td id="edit" align="center"><div>Edit</div></td><td id="assess" align="center"><div>Assess Training</div></td>**
And the html code is inside a while loop so you will have multiple div's with same id! You need to give them unique ids:
$i = 0;
while($rows=mysql_fetch_array($get)){
/* Code... */
<?php
$i = $i + 1;
}
?>
And
<div id="assess<?php echo $i ?>>
And in your javascript:
/* Code... */
if (rightNow < d ) {
var i = 0;
while(document.getElementById("assess" + i) != null) {
document.getElementById("assess").innerHTML = ""; /* make it disappear */
i++;
}
/* Code.../
It's a bit hard to tell what the resulting full HTML in the page looks like, but do you realize that you can only have one object in a web page with a given ID. So, you can't have multiple objects with id="assess". If that is what you're doing, then getElementById will likely only return the first one - though the exact behavior is undefined because it's not valid HTML.
Second, why not just use CSS to hide things rather than clearing the innerHTML. For example, you could use a class="assess" instead of the id="assess". And, then create a CSS rule like this:
.triggerHide .assess {display: none;}
Then, when you want to hide that all assess classes in the table, you simple add the class "triggerHide" to the table. Boom, all the objects with the class assess in the table will all hide.
Related
i have this table wrote in html with php and bootstrap:
<table id="tabela-resultado" class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th>Nome</th>
<th>Ativo</th>
<th class="text-center">Ação</th>
</tr>
</thead>
<tbody>
<?php if(count($records)) { ?>
<?php foreach($records as $record) { ?>
<tr data-id="<?php echo $record->id; ?>">
<td><?php echo $record->nome; ?></td>
<td>
<?php
if ($record->ativo == 1) {
echo "SIM";
} else if($record->ativo == 0){
echo "NÂO";
}
?>
</td>
<td>
<?php echo anchor("gurpoProduto/excluir", "<i class='glyphicon glyphicon-trash'></i> Exlcuir", ['class' => 'btn btn-danger btn-block', 'name' => 'delete']); ?>
</td>
</tr>
<?php
}
}
?>
</tbody>
</table>
i'm trying to found an element in the first column using this function with jquery. Tihs is the function:
function verificar_existencia(nome) {
var table = $("#tabela-resultado tbody");
var nomeTabela = '';
table.find('tr').each(function (nome) {
var $tds = $(this).find('td'),
nomeTabela = $tds.eq(0).text()
});
if(trim(nome.toUpperCase()) === trim(nomeTabela.toUpperCase())) {
toastr.success("This element already exists!!!", "Aviso");
//return false;
}
}
but doesnt work.Whats is wrong? I need find an element in the table to prevent duplicate elements in the table.
You are looping through all the rows and overwriting nomeTabela every iteration.
Thus once loop completes it is the value found in last row only and that is what your comparison is done on
Do a check inside the loop for each value on each row something like:
function verificar_existencia(nome) {
nome = nome.trim().toUpperCase();
var table = $("#tabela-resultado tbody");
var isMatch = false;
table.find('tr').each(function(nome) {
var $tds = $(this).find('td');
var nomeTabela = $(this).find('td').eq(0).text();
// compare each value inside the loop
if (nome === nomeTabela.trim().toUpperCase()) {
isMatch = true;
return false; /// break the loop when match found
}
});
if (isMatch) {
toastr.success("This element already exists!!!", "Aviso");
//return false;
}
}
Also note your incorrect use of String#trim() which should show up as error in your browser console
Here's a way to identify a dupe strings in the first column of the table.
var $trs = $("table tr"), dupes = [];
function san(str) {
return str.text().trim().toUpperCase();
}
$trs.each(function() {
var origTd = $(this).find("td:first"), origTr = $(this);
$trs.each(function() {
var newTd = $(this).find("td:first"),
newTr = $(this),
origTrIdx = origTr.index(),
newTrIdx = newTr.index(),
origTdStr = san(origTd),
newTdStr = san(newTd);
if (
origTrIdx > newTrIdx &&
dupes.indexOf(origTdStr) < 0 &&
origTdStr === newTdStr
) {
dupes.push(origTdStr);
console.log(
'This element "' +
origTd.text() +
'" already exists!!!'
);
return false;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table>
<tr>
<td>foo</td>
<td>bar</td>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
</tr>
<tr>
<td>unique</td>
<td>bar</td>
</tr>
<tr>
<td>unique2</td>
<td>bar</td>
</tr>
<tr>
<td>unique2</td>
<td>bar</td>
</tr>
<tr>
<td>unique2</td>
<td>bar</td>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
</tr>
</table>
I know that this question might have been asked before, but I can't figure it out.
AJAX is passing the selected date to PHP and it should dynamically update this $select with the data from AJAX and update the query made to teh database. But $_POST['date'] seems to be empty and nothing is happening.
AJAX
$(window).ready(function(event) {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){ dd='0'+dd; }
if(mm<10){ mm='0'+mm; }
var today = yyyy+'-'+mm+'-'+dd; // document.getElementById("DATE").value = today;
selectedDate = today; // selectedDate = '2016-04-17';
var options = {
selectedDate: selectedDate,
onSelectedDateChanged: function(event, date) {
var d = new Date(date);
passDate(d);
}
};
passDate(new Date(selectedDate));
$('#paginator').datepaginator(options);});
function passDate(d) {
date = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
console.log(date);
$.ajax({
data: date,
type: "POST",
url: "php/table_body.php"
});};
PHP
<?php
$select = $_POST['data'];
$sql_query="SELECT * FROM users where date = '$select'";
// $sql_query="SELECT * FROM users WHERE date = '2017-05-12'";
$result_set=mysql_query($sql_query);
if(mysql_num_rows($result_set)>0)
{
while($row=mysql_fetch_row($result_set))
{
?>
<tr>
<td><?php echo $row[1]; ?></td>
<td><?php echo $row[2]; ?></td>
<td><?php echo $row[3]; ?></td>
<td><?php echo $row[4]; ?></td>
<td><?php echo $row[5]; ?></td>
<td><?php echo $row[6]; ?></td>
<td><?php echo $row[7]; ?></td>
<td align="center"><span class="glyphicon glyphicon-edit"> Edit</td>
<td align="center"><span class="glyphicon glyphicon-trash"> Delete</td>
</tr>
<?php
}
}
else
{
?>
<tr>
<td colspan="5">No Data Found !</td>
</tr>
<?php
}
Can you help figure how to fix it. Thank you
In the ajax javascript:
data: { date: date },
You didn't define the variable key for the date.
Also change in the php
$select = $_POST['date'];
And as suggested in the comments code for SQL injection protection.
check your parameter on $.ajax for the data, it should be like
$.ajax({
url: "php/table_body.php",
method: "POST",
data: { date: date}
});
for more information visit this link for ajax ref http://api.jquery.com/jquery.ajax/
I'm using keypress via this OOP function below to update my sites shopping cart and quantity value. Sometimes it works, but most of the time when I press the enter key it doesn't a) update the cart nor b) update the qty value. I think it's refreshing the page, which could be the issue.
I took a look at the request header value by inspecting the qty element and that doesn't update when enter key pressed, if that helps.
function initBinds() {
if ($('.remove_basket').length > 0) {
$('.remove_basket').bind('click', removeFromBasket);
}
if ($('.update_basket').length > 0) {
$('.update_basket').bind('click', updateBasket);
}
if ($('.fld_qty').length > 0) {
$('.fld_qty').bind('keypress', function(e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code == 13) {
updateBasket();
}
});
}
}
And here's the updateBasket function
function updateBasket() {
$('#frm_basket :input').each(function() {
var sid = $(this).attr('id').split('-');
var val = $(this).val();
$.ajax({
type: 'POST',
url: '/mod/basket_qty.php',
data: ({ id: sid[1], qty: val }),
success: function() {
refreshSmallBasket();
refreshBigBasket();
},
error: function() {
alert('An error has occurred');
}
});
});
}
And, this is the page...
Note, you can see on line 41 the class of fld_qty is used for the initiBinds keypress function if statement.
<?php
$session = Session::getSession('basket');
$objBasket = new Basket();
$out = array();
if (!empty($session)) {
$objCatalogue = new Catalogue();
foreach ($session as $key => $value) {
$out[$key] = $objCatalogue->getProduct($key);
}
}
require_once('_header.php'); ?>
<div id="cat_prod"><h1>- BASKET -</h1></div>
<?php
if (!empty($out)) { ?>
<div id="big_basket">
<form action="" method="post" id="frm_basket">
<table cellpadding="0" cellspacing="0" border="0" class="tbl_repeat">
<tbody id="basket_table">
<tr style="background-color: #f2f3ee;">
<th class="ta_left">Item</th>
<th class="ta_r">Qty</th>
<th class="ta_r col_15">Price</th>
<th class="ta_r col_15"></th>
</tr>
<?php foreach ($out as $item) { ?>
<tr>
<td class="ta_left_name"><?php echo Helper::encodeHTML($item['name']); ?></td>
<td class="ta_left_qty"><input type="text" name="qty-<?php echo $item['id']; ?>"
id="qty-<?php echo $item['id']; ?>" class="fld_qty"
value="<?php echo $session[$item['id']]['qty']; ?>" /></td>
<td class="ta_r">£<?php echo number_format($objBasket->itemTotal($item['price'], $session[$item['id']]['qty']), 2); ?></td>
<td class="ta_r"> <?php echo Basket::removeButton($item['id']); ?></td>
</tr>
<?php } ?>
<?php if ($objBasket->_vat_rate != 0) { ?>
<tr style="border-bottom: dashed 1px #aaa">
<td class="ta_left" colspan="2">Sub-total :</td>
<td class="ta_r bt_td">£<?php echo number_format($objBasket->_sub_total, 2); ?></td>
<td class="ta_r bt_td"> </td>
</tr>
<tr style="border-bottom: dashed 1px #aaa">
<td class="ta_left" colspan="2">VAT (<?php $objBasket->_vat_rate; ?>%) :</td>
<td class="ta_r bt_td">£<?php echo number_format($objBasket->_vat, 2); ?></td>
<td class="ta_r bt_td"> </td>
</tr>
<?php } ?>
<tr>
<td class="ta_right" colspan="2"><strong>Total :</strong></td>
<td class="ta_r bt_td">£<?php echo number_format($objBasket->_total, 2); ?></td>
<td class="ta_r bt_td"> </td>
</tr>
</tbody>
</table>
<div class="dev br_td"> </div>
<div class="dev br_td"> </div>
<div class="sbm sbm_blue fl_r">
Checkout
</div>
<div class="sbm sbm_blue fl_l update_basket">
<span class="btn">Update</span>
</div>
</form>
</div>
<?php } else { ?>
<br />
<br />
<p><em>Your basket is currently empty.</em></p>
<?php } ?>
<?php require_once('_footer.php'); ?>
I have looked through some statckflow pages regarding this and have tried keydown and just using e.which and e.keyCode || e.which instead, but they all render the same issue of not working 100% of the time when you press enter key.
I understand some browsers may not support this, so is there a better approach for this operation? I have tested Firefox, Chrome and Safari (all latest).
Thanks for the help, appreciated! :)
Edit;
Here's the mod/basket_qty.php also...
<?php
require_once('../inc/autoload.php');
if (isset($_POST['qty']) && isset($_POST['id'])) {
$out = array();
$id = $_POST['id'];
$val = $_POST['qty'];
$objCatalogue = new Catalogue();
$product = $objCatalogue->getProduct($id);
if (!empty($product)) {
switch($val) {
case 0:
Session::removeItem($id);
break;
default:
Session::setItem($id, $val);
}
}
}
Looks like I needed to add e.preventDefault(); in the initBinds function for if (code == 13) { as pointed out by cmorrissey. It seems to be working fine with this. Thanks!!
I have the following Datatable
<br><button id="addRow">Add New Row</button><br>
<table class="table table-striped table-bordered table-hover " id="example" cellSpacing=0 width="100%">
<thead>
<tr>
<th>Image</th>
<th>number</th>
<th>Creation_date</th>
<th>ei</th>
<th>name</th>
<th>profit</th>
</tr>
</thead>
<?php
foreach ( $data_req_table as $k => $v ) :
?>
<tr style="text-align: center;">
<td>
<img width="100px"
data-original="image.jpg"
src="image.jpg"
/>
</td>
<td><? echo $v['number']; ?></td>
<td><? echo $v['creationdate']; ?></td>
<td><? echo $v['ei']; ?></td>
<td><? echo $v['name']; ?></td>
<td><? echo $v['profit']; ?></td>
</tr>
<?php
endforeach;
?>
</table>
on which I add rows trough a Jquery - Ajax script. following :
<script type="text/javascript">
$(document).ready(function () {
debugger;
var t = $('#example').DataTable({
"searching": true,
//"paging": true,
"order": [[ 2, "desc" ]],
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
], iDisplayLength: -1
});
var counter = 1;
$('#addRow').on('click', function ciicici() {
var now = new Date();
var now = now.toMysqlFormat();
var tii = new Date();
tii.setSeconds(tii.getSeconds() - 15);
var tii = tii.toMysqlFormat();
//alert(tii);
$.post( "sql.php", { timing: now,seconding: tii })//.done({});
.done(function( data ) {
var dataParts = data.split("##")
var lenghtylenght = dataParts.length;
for (i = 0; i <= lenghtylenght; i++) {
var dataPart = dataParts[i];
var splitData = dataPart.split("///");
t.row.add([
splitData[0],
splitData[1],
splitData[2],
splitData[3],
splitData[4],
splitData[5]
]).draw();
alert('done');
}
counter++;
});
//setTimeout(function(){ciicici();}, 15000);
});
$('#addRow').click();
});
</script>
and the php being
$ippi = 0;
foreach ( $data_rreq as $k => $v ) : //data_rreq is the pdo fetched array
$ippi++;
echo "<td><img width='100px' src='image.jpg' /></td>".'///';
echo '<td>'.$v['number'].'</td>'.'///';
echo '<td>'.$v['creationdate'].'</td>'.'///';
echo '<td>'.$v['ei'].'</td>'.'///';
echo '<td>'.$v['name'].'</td>'.'///';
echo '<td>'.$v['profit'].'</td>';
if($ippi < $len){
echo "##";
}
endforeach;
The code works but I have 2 problems :
1) Datatable problem, everytime a row is automatically added, I get an error : Requested unknown parameter '1' for row ... . It looks like it loops once too much, it doesn't find any results and it has an error. My datatable reference being the following :
<script src="http://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.0/js/jquery.dataTables.min.js"></script>
2) And then I wanted to ask wether there is a way to avoid using the split function to puss 5 different parameters to a request, using may be some sort of json encoded arrays.
markoc
I think your loop need to be patched:
for (i = 0; i <= lenghtylenght; i++)
Replace with:
for (i = 0; i < lenghtylenght; i++)
Else you will go outofindex.
I want to check the table row value on page load..
Table example:
Name || Status || Set
John || Pass || [ ] (checkbox)
Chris || Fail || [ ] (checkbox)
When the status is 'Fail' I want to disable the checkbox..
Now I'm using this jQuery:
<script>
$(document).ready(function() {
if(getElementsByClassName('paket_ava').value=='kosong'))
{
document.getElementById("checkboxx").disabled=true;
}
});
</script>
and this is my PHP table code :
<tr>
<td><?php echo $paket['id_paket'];?></td>
<td><?php echo $paket['nama_paket'];?></td>
<td><?php echo $paket['keterangan_paket'];?></td>
<td><?php echo $paket['harga'];?></td>
<td><img src='<?php echo $paket['gambar_paket']?>' width='120' height='120'></td>
<td class="paket_ava"><?php echo $paket['ketersediaan_paket'];?></td>
// class on the table data
<td><?php echo $paket['status_harian_paket'];?></td>
<td><input type="checkbox" name="chkDel[]" id="checkboxx" class="aku" value="<?=$paket["id_paket"];?>"></td>
<?php
echo ("<td><a href='edit_data_paket.php?id_paket=$paket[id_paket]'>Edit</a></td>");
?>
</tr>
The code above is not working, but if I change to:
if(getElementsByClassId('paket_ava').value=='kosong'))
{
document.getElementById("checkboxx").disabled=true;
}
(of course I change the class in the table into Id)
When the page load its acting strange and the checkbox on the first data is disabled..
How to do this properly?
Try like below.... It will help you...
Fiddle Example: http://jsfiddle.net/68wbx/126/
Suppose your HTML Table was like below:
HTML:
<table id="datapaket" border="1">
<tr>
<th>Name</th><th>Status</th><th>Set</th>
</tr>
<tr>
<td>John</td><td class="paket_ava">Pass</td>
<td><input type="checkbox" name="chkDel[]" id="checkboxx" class="aku" value='sam'/></td>
</tr>
<tr>
<td>Chris</td>
<td class="paket_ava">Fail</td>
<td><input type="checkbox" name="chkDel[]" id="checkboxx" class="aku" value='sam'/></td>
</tr>
</table>
and try the Below Jquery :
$(document).ready(function() {
$('#datapaket tr').each(function() { //Looping Every Table Row
//Get the TD Value that have Classname ".paket_ava"
var str = $(this).find('.paket_ava').html();
if(typeof str !== 'undefined'){
if (str.indexOf("Fail") >= 0)
$(this).find('td:nth-child(3) input:checkbox').attr("disabled", true);
};
});
});
traverse through each element having class 'paket_ava' and do your stuff inside it. like
$('.paket_ava').each(function(i, obj) {
// your stuff...
});
Reference : jQuery to loop through elements with the same class