conditionally format php output with javascript - javascript

I would like to conditionally apply (based on date and time) with Javascript different CSS styles on a <div> element that contains data output with Php from a Mysql database. The php generates a list of events into various <div>s, where a <div> would receive different coloring depending on the date/time it holds relative to the actual day. (So if the event date/time is in the future, the color would be blue, if in the past, grey.)
I understand a PHP solution would use the server's date/time, while javascript would use the browser's date/time, so I selected javascript for the conditional formatting based on date/time.
I also understand that javascript needs to wait until the whole page loads, including the result of the php query.
(I also understand that I know very little about javascript and php.)
Below is the html and php code I have. This php queries the first 10 events and presents them in a list ordered by date in a bootstrap table. The div #timecode is which I would like to conditionally format (this sample php code does not contain the pagination php code, and returns the first 10 records from the database):
<div class="row">
<div class="venuelista">
<div class="col-sm-9 col-md-9 col-lg-9">
<table class="table">
<tbody>
<?php
while ($row = mysql_fetch_assoc($rs_result)) {
?>
<tr>
<td class="col-md-7">
<div id="timecode" padding="right:5px"><?php echo $row['esemeny_disp_mm_dd']; ?></div>
<div class="eventListTitle"><?php echo $row['esemeny_cim']; ?><br><?php echo $row['esemeny_jelleg']; ?></div>
</td>
<td class="col-md-5">
<div class="eventListTitle"><?php echo $row['esemeny_helyszin']; ?>
</div>
</td>
</tr>
<?php
};
?>
</tbody>
</table>
</div>
</div>
In the Mysql database I have and 'event date' field and a separate 'event time' field.
And this is the javascript I found on the net, maybe on this site, to format the div #timecode on the basis of its date/time (this is just testing if it works against a fix date - it does):
<script>
$(document).ready(function() {
var curtime = new Date(),
curday = curtime.getDate(),
curmonth = curtime.getMonth()+1;
if(curmonth == 7 && curday == 20)
$('#timecode').addClass('circle-disappear-blue');
else
$('#timecode').addClass('circle-disappear-grey');
});
</script>
Problem: javascript only formats the very first php result of the list. I thought the $(document).ready(function() would allow it to format all 10 list items.
Again I am sorry for malformatting my question - I am not on mutual understanding with the code sample function.
Any insight into this is appreciated.
EDIT:
The javascript now looks like this
<script>
$(document).ready(function() {
$('#mytableid tr td:first-child').addClass('circle-disappear-blue');
var curtime = new Date(),
curday = curtime.getDate(),
curmonth = curtime.getMonth()+1;
if(curmonth == 7 && curday == 19)
$('#blue-condtional').addClass('circle-disappear-blue');
else
$('#blue-condtional').addClass('circle-disappear-grey');
});
</script>

add id to your table for example
<table class="table" id="mytableid">
then use proper selector
$('#mytableid tr td:first-child').addClass('circle-disappear-blue');
the other option is to add class to types that you want change color let's say "blue-condtional"
if(curmonth == 7 && curday == 20) {
$('.blue-condtional').addClass('circle-disappear-blue');
} else {
$('.blue-condtional').addClass('circle-disappear-grey');
}
and change
<div id="timecode" padding="right:5px">
to
<div class="blue-condtional">
btw using inline styles is not good habbit.

Related

Reload Data with .sort from Dynamic Table with Jquery | JSON | Sort with New Data

I have been trying for a few days that when I use the .sort property the data is eliminated or modified instead of it being reloaded as new lines.
Attach Captures from the code Working
Image1 How work the code when i press the button, this sort to the highest price to lowest but how do you can see in the second image, the code appears up and this not delete the old data
Marked with "X" the data that does not have to show
this fragment is the one that generates the tables dynamically
const mostrarProductos = () => {
$.getJSON(URLJSON, (respuesta) => {
for (let z of respuesta) {
productosv2.push(z);
}
for (let x of productosv2) {
$("#fila").append(`
<tr class="deleteProductos">
<div class="card text-center" style="width: 18rem;" id='btnBorrarCarrito'>
<div class="card-body">
<input type="hidden" id="idProd" value="${x.id}"> </td>
<td class="card-title" id="${x.id}">${x.producto}</h2> </td>
<td class="card-text">$ ${x.precio}</p></td>
<div class="btn-group" role="group" aria-label="Basic mixed styles example">
<td><button type="button" class="btn btn-success" onclick="agregarCarrito(${x.id})">Agregar</button></td>
</div>
</div>
</div>
</tr>
`);
}
$("#fila").fadeIn("5000");
});
};
And this function is what orders them
function respuestaClickExpensive() {
$("#fila").html('');
let productosordenados = productosv2.sort((a, b) => {
if (a.precio > b.precio) {
return -1;
}
if (a.precio < b.precio) {
return 1;
}
return 0;
});
return productosordenados;
}
The one that orders them from smallest to largest is the same only that different signs and names.
As you can see I tried to use a ".html ("")" since previously in another cart attempt it used .innerHtml (Which does not work in this case either, Also the code of the cart is totally different from that moment that it worked for me
)
I tried the following:
$ ("#fila"). empty ();
Make another function to clean with .empty
Use Native JavaScript to generate the code.
$ ("#fila"). remove (); this removes all the content for me but does not regenerate it.
Change the HTML tag "Row" to a previous div which, since the div was not generated again, did not generate it again.
$ ("#fila tr"). remove ();
And some more things that I don't remember right now.
If you can guide me on what I did wrong or any suggestions to fix it, I appreciate it.
If I had to follow a template about posting on StackOverFlow or having chosen or named in a different way, I appreciate your comment since it is my first post
Project notes of possible relevance: The complete code outside of html and css is made with Native JavaScript, Jquery, Ajax, SASS and BootStrap.

Php show info after a set date

Hi and thanks for taking the time to look at my question. I currently have a Php script that allows me to hide content after a set date and replace it with a default text, you can see it below:
<?php if (date('Y-m-d') <= '2018-05-30') { ?>
<li><p><strong>Apply to Graduate:</strong></p>
<p>Apply to Graduate</p>
</li>
<?php } else { ?>
<p><li><strong>The application to graduate is not available at this time.</strong> If you qualify to graduate, the Registrar’s Office will notify you when the application to graduate is available.</li></p>
<?php } ?>
What I am trying to do now is add an extra script that turns it back on in a set date so basically it functions both ways, hiding content after a set date and then activate the content once another date comes, I have been having a hard time figuring it out and I would love if you can give me a hand!
Thanks a lot for your time and your help.
The logic would be to add the latest date first and the earliest last. Something like:
if date >= 2018-08-30
what happens after the second date
elseif date <= 2018-05-30
What happens before the first date
else
What happens in between
This works because once a condition is fulfilled it breaks off the else/if statement.
Personally, I would do it like this if you are hardcoding dates, mainly so I don't have to come back to the script too much ;p
Have an array of dates, then match the closest start date then check that today is between the start and end of the matched array.
<?php
$dates = [
['start' => '2018-05-30', 'end' => '2018-06-30'],
['start' => '2018-07-26', 'end' => '2018-08-30'], // matches this
['start' => '2018-09-30', 'end' => '2018-10-30'],
];
function closest_key($dates, $date) {
$result = [];
foreach($dates as $value) {
$result[] = abs(strtotime($date) - strtotime($value));
}
asort($result);
return key($result);
}
$today = date('Y-m-d');
$date = $dates[closest_key(array_column($dates, 'start'), $today)];
if ($today >= $date['start'] && $today <= $date['end']) {
echo 'Apply to Graduate';
} else {
echo 'The application to graduate is not available at this time.';
}
Result (today is 2018-07-27):
Apply to Graduate
https://3v4l.org/LGpv8
If the date was 2018-09-01 it would be false.
The same idea could also be done in Javascript, with a little porting.
Updated answer.
Say, based on the scenario in your question and comment the offer expires first time after 5 days from today $currentdate which is your $first_expire_date. if you want to start the offer 2nd time again after 10 days from today & keep continue it for further 15 days from 2nd time offer start date, you shall try to use,
<?php
// Today
$currentdate = date('Y-m-d');
// Offer starts. Set it as you want. You can set it to '2018-05-30' in that case you already get $first_expire_date expires.
$offer_start_date = '2018-07-28';
// You can add +220 days, or +1 month or +2 years in the following snippet as you prefer
// You can also subtract -3 months or -11 years or -1 day as you need
$first_expire_date = date('Y-m-d',strtotime('+5 days',strtotime($offer_start_date )));
//2nd time offer start date
$second_valid_date_start = date('Y-m-d',strtotime('+5 days',strtotime($first_expire_date)));
//2nd time offer end date
$second_valid_date_end = date('Y-m-d',strtotime('+15 days',strtotime($second_valid_date_start)));
?>
<?php if ($currentdate <= $first_expire_date) { ?>
<li><p><strong>Apply to Graduate:</strong></p>
<p>Apply to Graduate</p>
</li>
<?php }else ?>
<?php if (isset($second_valid_date_start) && ($second_valid_date_start <= $second_valid_date_end)) { ?>
<li><p><strong>Apply to Graduate:</strong></p>
<p>Apply to Graduate</p>
</li>
<?php }else{ ?>
<p><li><strong>The application to graduate is not available at this time.</strong> If you qualify to graduate, the Registrar’s Office will notify you when the application to graduate is available.</li></p>
<?php } ?>
I hope it helps.

Hover Event in Javascript/PHP/Codeigniter

To give some Background information: I've got a php-function "showSystems" which extracts data from our CMDB and shows it in a Dropdown generated by the Codeigniter form helper "form_dropdown". So the dropdown contains the names of all our servers and when clicking on one, some other unrelevant functions show different kinds of information about that particular system.
What I want to achieve now is, when hovering over a system listed in the dropdown, that the description of that system is shown in a label under the list. When nothing is hovered, the label is hidden.
Something like:
Dropdown:
Server1
Server2 <-- hover over this
Server3
Label --> shows Description of Server2
How can I handle the mosehover-event in this generated dropdown using php/javascript?
Edit: So I give some more background-information, as it seems to have something to do with my technical setup.
The function, which produces the dropdown with the received data is written in a model of Codeigniter:
<?php
echo '<select class="minipanel" id="selectminipanel" size="25" style="width: 100%" onchange="window.location = \''.site_url(CONTROLLER.'/showItem').'/\' + this.value;">';
foreach($tmp as $key => $value):
if ($active == $key){
echo '<option onmouseover="displayDescription(this)" onmouseout="hideLabel()" value="'.$key.'" server-description="'.$value[1].'" selected>'.$value[0].'</option>';
} else {
echo '<option onmouseover="displayDescription(this)" onmouseout="hideLabel()" value="'.$key.'" server-description="'.$value[1].'">'.$value[0].'</option>';
}
endforeach;
echo '</select>';
?>
The modul is loaded in a template via a view(which loads the model). The label is defined right after the codeigniter call:
<?php $this->load->view("V".$this->name."/vMinipanel"); ?>
<label id="description"></label>
The script is also written in this template's head section:
<script language="JavaScript">
function displayDescription($ele) {
var server_data = ele.server-description;
document.getElementById('description').innerHTML = server_data;
}
function hideLabel() {
document.getElementById('description').innerHTML ='';
}
</script>
So, why are the functions displayDescription and hideLabel not called?
Please check and run below code:
server 1<br>
server 2<br>
server 3
If you are using bootstrap
server 1
server 2
server 3
just these lines of codes will work fine for you .
trigger an event on mouse over, and use the element's data-description to show the details:
<option onmouseover="displayDescription(this)" onmouseout="hideLabel()" data-server-description="your_description" id='1'>
Server1
</option>
<script>
function displayDescription(ele)
{
// You can use the data-server-description attribute to catch the description
var server_data = ele.data-server-description;
// you can also use the ID to fetch the description if not embadded in as an html attribute
var server_id = ele.id;
document.getElementById('your_label_id').innerHTML = server_data;
}
function hideLabel()
{
document.getElementById('your_label_id').innerHTML ='';
}
</script>

Getting top five rows from a populated table element

I have a table (called mytbl - see below) consisting of 100 rows. From this table, I want to take only the first five rows (assume a user presses "Show Top Five")
This is what I have tried, however, the alert gives me 'empty'
var $updatedtable = $("#mytbl");
$updatedtable.empty();
for ( var i = 0; i < 5; i++ )
{
$updatedtable.append(document.getElementById("mytbl").rows.item(i).innerHTML)
}
alert($updatedtable);
$updatedtable.appendTo( $( "#rbl" ) );
This was the code used to create the html page
<div class="tab-pane" id="rbl">
<div id="rbldiv">
<div class="bs-example voffset-10px">
<form>
<div class="form-group">
<label for="inputText" style="float:left;margin-right:5px;">Show top </label>
<div class="col-xs-1">
<input type="text" class="form-control input-normal" id="ben-count-set" placeholder="100">
</div>
<label for="inputText"> beneficiaries by cost increase</label>
</div>
</form>
</div>
<table id="mytbl" class="table table-striped table-hover"></table>
</div>
</div>
Also, if, after I successfully manage to get the top five and appendTo rbl which has mytbl, won't this get overwritten? If later the user wants to See Top 30, aren't the values gone? How can I take care of this?
EDIT:
I was able to get the display of the top rows thanks to charlietfl and Tatermelon. But my rows get sliced off, and I haven't completely understood how to handle a case where user selects top 10 first and then top 11.
This is what I have tried.
In the function where I'm making the (entire) table for the first time, I saved the table as follows
function makeTable() {
//code to make table rbltbl
//code to make table rbltbl
//code to make table rbltbl
//code to make table rbltbl
//below line saves the table to $rows, so I can use it inside the click function below
$rows = $('#rbltbl tr').clone();
}
This is my function. Assume 'ben-count-set' is the number of values, the user wants to see. I think I should change var $table to read from $rows instead of rbltbl. But $rows gives empty here.
$("#ben-count-submit").click(function (event) {
event.preventDefault();
console.log("clicked on the update button");
var reqcount = document.getElementById('ben-count-set').value;
var $table = $("#rbltbl");
var $mystring = '#rbltbl tr:gt('+parseInt(reqcount)+')';
$($mystring).remove();
console.log($mystring);
$table.appendTo( $( "#rbl" ) );
}
Please advise.
If you want an array of the first 5 rows can get it right in a jQuery object using several different selectors
$('#mytbl tr:lt(5)');
You can can cache all the rows into a variable and still have access to them later regardless of what you do to the table...just clone them
var $rows = $('#mytbl tr').clone();
Want to remove all but top 5
$('#mytbl tr:gt(4)').remove();
then change out for another selection of rows clone the clone, filter them and insert
$('#mytbl').html( $rows.clone().slice(5, 10) );
If you are using jquery, then you can use the :lt selector:
var $firstRows = $('#mytbl').find('tr:lt(5)');
Then, you can clone them to append in your new table so that they will not be removed from your original table:
$( "#rbl" ).append($firstRows.clone());

split a big HTML page to pages on client side

I have a huge HTML page which is mainly a form which is mostly like this:
<FIELDSET id= '1'>
<TABLE>
<TR> </TR>
</FIELDSET>
</TABLE>
.
.
.
<FIELDSET id= 'n'>
<TABLE>
<TR> </TR>
</TABLE>
The number of fieldsets are generated by dynamically on the server.
Question: On the client side I want to do a pagination for this huge page, so that only say,3 fieldset appear per page on the client.
I don't want to change the way page is loading or form is being submitted currently.
Well just a little tips you may use
$('fieldset')
document.querySelectorAll('fieldset')
will return you fields
in order to get show only i .. i+3 fieldsets you can use
var i = 3
$('fieldset').hide().each(function ( index, el) {
if (index >= i && index < i+3) $(el).show()
})
var fieldsets = [].slice(document.querySelectorAll('fieldset'))
for (var index in fieldsets) {
var display = index < i && index >= i+3 ? 'none' : ''
fieldsets[index].style.display = display
}
Pagination won't really help you in any way other than visual if done on the client side (no speed increases, load reductions, etc), but if that's what you want you can do it with DOM manipulation. Something like the following might work for you:
var i=0,sets=document.getElementsByTagName('fieldset'),len=sets.length;
for(;i<len;i+=3) {
// wrap sets[i] through sets[i+2], as long as they exist, in a div
// if i !== 0, hide or minimize the div
}
// add controls to unhide/unminimize each div

Categories