JQuery turns the form input field :
<form method="post" action="./action.php">
<input type="text" class="timepicker" name="timepicker" id="timepicker" />
.
.
</form>
into
JQuery :
/* jQuery timepicker
* replaces a single text input with a set of pulldowns to select hour, minute, and am/pm
*
* Copyright (c) 2007 Jason Huck/Core Five Creative (http://www.corefive.com/)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* Version 1.0
*/
(function($){
jQuery.fn.timepicker = function(){
this.each(function(){
// get the ID and value of the current element
var i = this.id;
var v = $(this).val();
// the options we need to generate
var hrs = new Array('01','02','03','04','05','06','07','08','09','10','11','12');
var mins = new Array('00','15','30','45');
var ap = new Array('am','pm');
// default to the current time
var d = new Date;
var h = d.getHours();
var m = d.getMinutes();
var p = (h >= 12 ? 'pm' : 'am');
// adjust hour to 12-hour format
if(h > 12) h = h - 12;
// round minutes to nearest quarter hour
for(mn in mins){
if(m <= parseInt(mins[mn])){
m = parseInt(mins[mn]);
break;
}
}
// increment hour if we push minutes to next 00
if(m > 45){
m = 0;
switch(h){
case(11):
h += 1;
p = (p == 'am' ? 'pm' : 'am');
break;
case(12):
h = 1;
break;
default:
h += 1;
break;
}
}
// override with current values if applicable
if(v.length == 7){
h = parseInt(v.substr(0,2));
m = parseInt(v.substr(3,2));
p = v.substr(5);
}
// build the new DOM objects
var output = '';
output += '<select id="h_' + i + '" class="h timepicker">';
for(hr in hrs){
output += '<option value="' + hrs[hr] + '"';
if(parseInt(hrs[hr]) == h) output += ' selected';
output += '>' + hrs[hr] + '</option>';
}
output += '</select>';
output += '<select id="m_' + i + '" class="m timepicker">';
for(mn in mins){
output += '<option value="' + mins[mn] + '"';
if(parseInt(mins[mn]) == m) output += ' selected';
output += '>' + mins[mn] + '</option>';
}
output += '</select>';
output += '<select id="p_' + i + '" class="p timepicker">';
for(pp in ap){
output += '<option value="' + ap[pp] + '"';
if(ap[pp] == p) output += ' selected';
output += '>' + ap[pp] + '</option>';
}
output += '</select>';
// hide original input and append new replacement inputs
$(this).attr('type','hidden').after(output);
});
$('select.timepicker').change(function(){
var i = this.id.substr(2);
var h = $('#h_' + i).val();
var m = $('#m_' + i).val();
var p = $('#p_' + i).val();
var v = h + ':' + m + p;
$('#' + i).val(v);
});
return this;
};
})(jQuery);
$(document).ready(function() {
$('.timepicker').timepicker();
});
/* SVN: $Id: jquery.timepicker.js 456 2007-07-16 19:09:57Z Jason Huck $ */
On form submit, as I try to get the default value of the field using $_POST['timepicker'] , I get a blank.
Why is that ? How can I get the default value from the field ?
The code dynamically creates some <select> elements for the hours and minutes but these do not have a name attribute so they are not submitted when the form is POSTed.
The value from these selects is saved into a hidden form field which has a name attribute (and so get's POSTed) - but this only happens when a value in the <select> elements is changed.
To allow the default to be submitted, you can manually trigger the "change" event in your "ready" function, like this:
$(document).ready(function() {
$('.timepicker').timepicker();
$('.timepicker').trigger('change');
});
Related
FYI, I am working on localhost with wampserver, using PHP and AJAX, trying to display the JSON data rows (which are around 1526). and the problem is i am not able to display the rows which are based on the search conditions.
Output of print_r($result_array); in console output as below. here in below pic don't worry for console error this error is becoz of PHP array used in parsing JSON. This output i used to test weather my server PHP file is working correctly or not but it is working correctly.
After that i checked my encoding function, for which output of echo json_encode($result_array); i am getting red console error for some search condition and in other search condition i am able to display results correctly.
For example, below two images
I am not able to figure out what is happening to my code.
File search.php
<?php
// send a JSON encoded array to client
include('connection.php');
$sqlFlag = 0;
function queryDelimiter(){
global $sqlFlag;
if ($sqlFlag == 0){
$sqlFlag = 1;
return ' WHERE ';
}else{
return ' AND ';
}
}
$selectSQL = "SELECT * FROM tbl_main_lead_info";
if(isset($_POST['lead_status']) and strlen(trim($_POST['lead_status'])) > 0){
$selectSQL .= queryDelimiter()."LeadStatus = '".$_POST['lead_status']."'";
}
if(isset($_POST['lead_owner']) and strlen(trim($_POST['lead_owner'])) > 0){
$selectSQL .= queryDelimiter()."LeadAddedBy = '".$_POST['lead_owner']."'";
}
if(isset($_POST['company_name']) and strlen(trim($_POST['company_name'])) > 0){
$selectSQL .= queryDelimiter()."Company = '".$_POST['company_name']."'";
}
if(isset($_POST['tech_area']) and strlen(trim($_POST['tech_area'])) > 0){
$selectSQL .= queryDelimiter()."TechArea = '".$_POST['tech_area']."'";
}
if(isset($_POST['firm_size']) and strlen(trim($_POST['firm_size'])) > 0){
$selectSQL .= queryDelimiter()."FirmSize = '".$_POST['firm_size']."'";
}
if(isset($_POST['firm_type']) and strlen(trim($_POST['firm_type'])) > 0){
$selectSQL .= queryDelimiter()."FirmType = '".$_POST['firm_type']."'";
}
if(isset($_POST['country_name']) and strlen(trim($_POST['country_name'])) > 0){
$selectSQL .= queryDelimiter()."Country = '".$_POST['country_name']."'";
}
if(isset($_POST['state_name']) and strlen(trim($_POST['state_name'])) > 0){
$selectSQL .= queryDelimiter()."State = '".$_POST['state_name']."'";
}
if(isset($_POST['city_name']) and strlen(trim($_POST['city_name'])) > 0){
$selectSQL .= queryDelimiter()."City = '".$_POST['city_name']."'";
}
if(isset($_POST['start_date']) and strlen(trim($_POST['start_date'])) > 0){
$selectSQL .= queryDelimiter()."LastContactDate >='".$_POST['start_date']."'";
}
if(isset($_POST['end_date']) and strlen(trim($_POST['end_date'])) > 0){
$selectSQL .= queryDelimiter()."NextContactDate <= '".$_POST['end_date']."'";
}
$selectSQL .= " ORDER BY FirstName ASC, LastName ASC, Lead_Id ASC";
$result_array = array();
$result = $conn -> query ($selectSQL);
if(mysqli_num_rows($result) > 0){
while ($row = $result->fetch_assoc()) {
array_push($result_array, $row);
}
}
// print_r($result_array);
echo json_encode($result_array);
// $selectSQL = "SELECT * FROM tbl_main_lead_info as M, tbl_campaign_info as C";
$conn->close();
?>
File loadtable.js
// This is script to load table based on filter section
$(document).ready(function() {
// Campaign Submit Info
$('[name="search_submit"]').click(function(e) {
$('#load-csv-file-button').attr('style','display:none;');
$("#filterRecords").attr('style','display:block;');
$('#add_lead_info').attr('style','display:none;');
e.preventDefault();
// GET the admin and user id value
var adminvalue = $('#filterformpost').find('[name="adminvalue"]').val();
var useridvalue = $('#filterformpost').find('[name="useridvalue"]').val();
var lead_owner = $('#filterformpost').find('#lead_owner_select option:selected').val();
var lead_status = $('#filterformpost').find('#lead_status_select option:selected').val();
var company_name = $('#filterformpost').find('#company_name_select option:selected').val();
var tech_area = $('#filterformpost').find('#tech_area_select option:selected').val();
var firm_size = $('#filterformpost').find('#firm_size_select option:selected').val();
var firm_type = $('#filterformpost').find('#firm_type_select option:selected').val();
var country_name = $('#filterformpost').find('#country_name_select option:selected').val();
var city_name = $('#filterformpost').find('#city_name_select option:selected').val();
var state_name = $('#filterformpost').find('#state_name_select option:selected').val();
var start_date = $('#filterformpost').find('#start_date_search').val();
var end_date = $('#filterformpost').find('#end_date_search').val();
// console.log('adminvalue: '+adminvalue)
// console.log('useridvalue: '+useridvalue)
// console.log('lead_owner: '+lead_owner)
// console.log('country_name: '+country_name)
// console.log('State: '+state_name)
$.ajax({
type: "POST",
url: "./server/search.php",
data: {
"lead_owner": lead_owner,
"lead_status": lead_status,
"company_name": company_name,
"tech_area": tech_area,
"firm_size": firm_size,
"firm_type": firm_type,
"country_name": country_name,
"city_name": city_name,
"state_name": state_name,
"start_date": start_date,
"end_date": end_date
},
beforeSend: function() {
$('.search_lead_filter_message_box').html(
'<img src="tenor.gif" width="40" height="40"/>'
);
},
success:function(data){
// console.log(data)
console.log("Data Length: "+data.length)
console.log(data)
if(data.length == 0){
$('.search_lead_filter_message_box').html('');
$("#filterRecords").html('No results fetched');
}
var result = $.parseJSON(data);
// console.log(result)
//###########################################
// Pagination code start
//###########################################
$('.search_lead_filter_message_box').html('');
$("#filterRecords").empty();
//###########################################
// Pagination code end
//###########################################
$("#pagination").attr('style', 'display:block;');
$("#number_of_rows").attr('style','display:block;');
$('#button-prev-next').attr('style','display:block;');
paginate_json_data(result, adminvalue, useridvalue)
}
});
});
});
function paginate_json_data(userDetails, adminvalue, useridvalue) {
adminvalue = adminvalue
useridvalue = useridvalue
userDetails = userDetails
var table = '';
table = $("<table></table>");
$('#pagination').html('<div id="nav-numbers" class="col nav"></div>');
$('#number_of_rows').html('');
$('#number_of_rows').html('<p1>Total number of leads fetched: ' + userDetails.length + '</p1>');
$('#button-prev-next').html('<button class="col PreviousButton" id="PreValue"><i class="ion-skip-backward"></i> Previous</button><button class="col NextButton" id="nextValue">Next <i class="ion-skip-forward"></i></button>');
var max_size = userDetails.length;
var sta = 0;
var elements_per_page = 10;
var limit = elements_per_page;
if(max_size<10){
// #####################################
// NUMBER OF ROWS A < 10 START START
// #####################################
table.append('<thead><th>#</th><th>Name</th><th>Company</th><th>Website</th><th>Designation</th><th>Email</th><th style="width: 150px;">Phone</th><th>City</th><th>State</th><th>Country</th><th>Lead Status</th></thead>');
table.append('<tbody id="myTable"></tbody>');
goFun_Modified(sta, max_size);
function goFun_Modified(sta, limit) {
for (var i = sta; i < limit; i++) {
var tab = '<tr><td>' + (i+1) + "\n" + '</td><td>' + "<a target='_blank' href=./lead/index.php?lead_id=" + userDetails[i].Lead_Id + " </a>" + userDetails[i].FirstName + ' ' + userDetails[i].LastName + "\n" + '</td><td>' + userDetails[i].Company + "\n" + '</td><td>' + userDetails[i].Website + "\n" + '</td><td>' + userDetails[i].Designation + "\n" + '</td><td>' + "" + userDetails[i].Email + "" + "\n" + '</td><td style="width: 150px;" >' + userDetails[i].Phone + "\n" + '</td><td>' + userDetails[i].City + "\n" + '</td><td>' + userDetails[i].State + "\n" + '</td><td>' + userDetails[i].Country + "\n" + '</td><td>' + userDetails[i].LeadStatus + "\n" + '</td></tr>';
console.log(tab)
$('#myTable').append(tab)
}
} // Function ended
$("#filterRecords").html(table);
$('#nextValue').click(function() {
// checks if it's the last page
if (currentPage < maxPage) {
currentPage++;
$pagingBtn.removeClass('active');
$pagingBtn.eq(currentPage).addClass('active')
} else {
alert("End of page");
}
});
$('#PreValue').click(function() {
// checks if it's the first page
if (currentPage > 0) {
currentPage--;
$pagingBtn.removeClass('active');
$pagingBtn.eq(currentPage).addClass('active')
} else {
alert("Start of page")
}
});
var number = Math.round(userDetails.length / elements_per_page);
for (i = 0; i <= number; i++) {
$('.nav').append('<button class="nav-numbers btn" id=' + i + '>' + (i+1) + '</button>');
}
$('.nav button').click(function() {
var start = $(this).text()-1;
// $(this).css({"background-color": "#e67e22", "color": "#ffffff"});
$('#myTable').empty();
limit = 10 * (parseInt(start) + 1) > max_size ? max_size : 10 * (parseInt(start) + 1)
goFun_Modified(start * 10, limit);
let $self = $(this);
// gets index of button relative to it's siblings
// https://api.jquery.com/index/
currentPage = $self.index();
$pagingBtn.removeClass('active');
$self.addClass('active');
});
// saves all the paging buttons for reusing, instead of calling $() every time
let $pagingBtn = $('#nav-numbers .btn');
let maxPage = $pagingBtn.length - 1;
let currentPage = 0;
$('.nav button')[0].click()
// #####################################
// NUMBER OF ROWS A < 10 END
// #####################################
}else{
// #####################################
// NUMBER OF ROWS A > 10 START
// #####################################
table.append('<thead><th>#</th><th>Name</th><th>Company</th><th>Website</th><th>Designation</th><th>Email</th><th>Phone</th><th>City</th><th>State</th><th>Country</th><th>Lead Status</th></thead>');
table.append('<tbody id="myTable"></tbody>');
goFun(sta, limit);
function goFun(sta, limit) {
for (var i = sta; i < limit; i++) {
var tab = '<tr><td>' + (i+1) + "\n" + '</td><td>' + "<a target='_blank' href=./lead/index.php?lead_id=" + userDetails[i].Lead_Id + " </a>" + userDetails[i].FirstName + ' ' + userDetails[i].LastName + "\n" + '</td><td>' + userDetails[i].Company + "\n" + '</td><td>' + userDetails[i].Website + "\n" + '</td><td>' + userDetails[i].Designation + "\n" + '</td><td>' + "" + userDetails[i].Email + "" + "\n" + '</td><td>' + userDetails[i].Phone + "\n" + '</td><td>' + userDetails[i].City + "\n" + '</td><td>' + userDetails[i].State + "\n" + '</td><td>' + userDetails[i].Country + "\n" + '</td><td>' + userDetails[i].LeadStatus + "\n" + '</td></tr>';
$('#myTable').append(tab)
}
$("#filterRecords").html(table);
}// FUNCTION ENDED
$('#nextValue').click(function() {
var next = limit;
if (max_size >= next) {
def = limit + elements_per_page;
limit = def
$('#myTable').empty();
if (limit > max_size) {
def = max_size;
}
goFun(next, def);
}
// checks if it's the last page
if (currentPage < maxPage) {
currentPage++;
$pagingBtn.removeClass('active');
$pagingBtn.eq(currentPage).addClass('active')
} else {
alert("End of page");
}
});
$('#PreValue').click(function() {
var pre = limit - (2 * elements_per_page);
if (pre >= 0) {
limit = limit - elements_per_page;
$('#myTable').empty();
goFun(pre, limit);
}
// checks if it's the first page
if (currentPage > 0) {
currentPage--;
$pagingBtn.removeClass('active');
$pagingBtn.eq(currentPage).addClass('active')
} else {
alert("Start of page")
}
});
var number = Math.round(userDetails.length / elements_per_page);
for (i = 0; i <= number; i++) {
$('.nav').append('<button class="nav-numbers btn" id=' + i + '>' + (i+1) + '</button>');
if(i == number){
}
}
$('.nav button').click(function() {
var start = $(this).text()-1;
$('#myTable').empty();
limit = 10 * (parseInt(start) + 1) > max_size ? max_size : 10 * (parseInt(start) + 1)
goFun(start * 10, limit);
let $self = $(this);
// gets index of button relative to it's siblings
// https://api.jquery.com/index/
currentPage = $self.index();
$pagingBtn.removeClass('active');
$self.addClass('active');
});
// saves all the paging buttons for reusing, instead of calling $() every time
let $pagingBtn = $('#nav-numbers .btn');
let maxPage = $pagingBtn.length - 1;
let currentPage = 0;
$('.nav button')[0].click()
// #####################################
// NUMBER OF ROWS A > 10 END
// #####################################
}
}
Updated:
Try add content-type specs to http header:
header("Content-Type: application/json");
and set UNICODE feature in json_encode:
echo json_encode($result_array, JSON_UNESCAPED_UNICODE);
I have a function that displays a countup timer but I've only been able to make it work for a single row. I'd like to make a timer appear on each row where the end time of the action has not yet been set.
This is the full code.
<script>
$('document').ready(function()
{
var uni_id = //value of id needed to query the database table;
$.ajax({
type : 'POST',
url : 'get_time.php',
dataType: 'json',
data : {uni_id: uni_id},
cache: false,
success : function(result)
{
for (var i = 0; i < result.length; i++){
var startDateTime = new Date(result[i].uni_start_time); //Not sure if it's wrong to add all returning values here but so far it works but only for a single row on the table.
var startStamp = startDateTime.getTime();
var newDate = new Date();
var newStamp = newDate.getTime();
var timer;
var rec_id = result[i].rec_id;
function updateTimer() {
newDate = new Date();
newStamp = newDate.getTime();
var diff = Math.round((newStamp-startStamp)/1000);
var days = Math.floor(diff/(24*60*60));
diff = diff-(days*24*60*60);
var hours = Math.floor(diff/(60*60));
diff = diff-(hours*60*60);
var minutes = Math.floor(diff/(60));
diff = diff-(minutes*60);
var seconds = diff;
days = (String(days).length >= 2) ? days : '0' + days;
hours = (String(hours).length >= 2) ? hours : '0' + hours;
minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;
$("#on_going_"+rec_id).html(hours+':'+minutes+':'+seconds);
}
setInterval(updateTimer, 1000);
$('#uni_time_table tbody').append(
'<tr>'
+'<td class="center hidden" id="'+result[i].rec_id+'">' + result[i].rec_id + '</td>'
+'<td class="center">' + result[i].uni_id + '</td>'
+'<td>' + result[i].uni_name + '</td>'
+'<td>' + result[i].uni_loc + '</td>'
+'<td class="center">' + result[i].uni_date + '</span></td>'
+'<td class="center">' + result[i].uni_start_time + '</td>'
+(result[i].uni_end_time == null ?
'<td class="center"></td>' //this will always be empty if the uni_end_time is not set.
:
'<td class="center">' + result[i].uni_end_time + '</td>'
)
+(result[i].uni_end_time == null ?
'<td class="center" id="on_going_'+result[i].rec_id+'"></td>' //the timer will only be triggered here if the uni_end_time is not set.
:
'<td class="center">' + result[i].uni_total_time + '</td>' //this will display the total time as long as the uni_end_time is set.
)
+'</tr>');
}
}
});
});
</script>
So far, only the first entry in the table displays the timer. Every time I add another entry, that second entry just remains blank while the timer still works with the first entry.
How can I make the timer work for each row on the table?
EDIT: Sample Data from json
rec_id "1"
uni_date "2016-10-28"
uni_loc "Custom Location"
uni_id "2356"
uni_name "Custom Name"
uni_start_time "10/28/2016 09:04:28"
uni_end_time null
uni_total_time null // this shows null because end_time is empty which is when the timer should kick in.
Here is a solution for you with little modifications of your code:
var startStamp = [];
function updateTimer(result) {
var newDate = new Date();
var newStamp = newDate.getTime();
for (var j = 0; j < result.length; j++) {
newDate = new Date();
newStamp = newDate.getTime();
var diff = Math.round((newStamp-startStamp[j])/1000);
var days = Math.floor(diff/(24*60*60));
diff = diff-(days*24*60*60);
var hours = Math.floor(diff/(60*60));
diff = diff-(hours*60*60);
var minutes = Math.floor(diff/(60));
diff = diff-(minutes*60);
var seconds = diff;
days = (String(days).length >= 2) ? days : '0' + days;
hours = (String(hours).length >= 2) ? hours : '0' + hours;
minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;
$("#on_going_"+result[j].rec_id).html(hours+':'+minutes+':'+seconds);
}
}
$('document').ready(function()
{
var uni_id = 1;//
$.ajax({
type : 'POST',
url : 'get_time.php',
dataType: 'json',
data : {uni_id: uni_id},
cache: false,
success : function(result) {
for (var i = 0; i < result.length; i++) {
var startDateTime = new Date(result[i].uni_start_time);
startStamp[i] = startDateTime.getTime();
$('#uni_time_table tbody').append(
'<tr>'
+ '<td class="center hidden" id="' + result[i].rec_id + '">' + result[i].rec_id + '</td>'
+ '<td class="center">' + result[i].uni_id + '</td>'
+ '<td>' + result[i].uni_name + '</td>'
+ '<td>' + result[i].uni_loc + '</td>'
+ '<td class="center">' + result[i].uni_date + '</span></td>'
+ '<td class="center">' + result[i].uni_start_time + '</td>'
+ (result[i].uni_end_time == null ?
'<td class="center"></td>' //this will always be empty if the uni_end_time is not set.
:
'<td class="center">' + result[i].uni_end_time + '</td>'
)
+ (result[i].uni_end_time == null ?
'<td class="center" id="on_going_' + result[i].rec_id + '"></td>' //the timer will only be triggered here if the uni_end_time is not set.
:
'<td class="center">' + result[i].uni_total_time + '</td>' //this will display the total time as long as the uni_end_time is set.
)
+ '</tr>');
}
setInterval((function () {
updateTimer(result);
}), 1000);
}
});
});
There is some weird thing happening. Following html with jquery generates a time picker. If I submit the default values to actiont.php a blank string gets printed by the script.
Why is that ? (Here is the jsfiddle with the output of jquery and html)
HTML:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="jquery.timepicker.js" type="text/javascript"></script>
<title> </title>
</head>
<body>
<form action="actiont.php" method="post">
<input type="text" class="timepicker" name="timepicker" id="timepicker" /> <br />
<input type="submit" />
</form>
</body>
JQuery:
/* jQuery timepicker
* replaces a single text input with a set of pulldowns to select hour, minute, and am/pm
*
* Copyright (c) 2007 Jason Huck/Core Five Creative (http://www.corefive.com/)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* Version 1.0
*/
(function($){
jQuery.fn.timepicker = function(){
this.each(function(){
// get the ID and value of the current element
var i = this.id;
var v = $(this).val();
// the options we need to generate
var hrs = new Array('01','02','03','04','05','06','07','08','09','10','11','12');
var mins = new Array('00','15','30','45');
var ap = new Array('am','pm');
// default to the current time
var d = new Date;
var h = d.getHours();
var m = d.getMinutes();
var p = (h >= 12 ? 'pm' : 'am');
// adjust hour to 12-hour format
if(h > 12) h = h - 12;
// round minutes to nearest quarter hour
for(mn in mins){
if(m <= parseInt(mins[mn])){
m = parseInt(mins[mn]);
break;
}
}
// increment hour if we push minutes to next 00
if(m > 45){
m = 0;
switch(h){
case(11):
h += 1;
p = (p == 'am' ? 'pm' : 'am');
break;
case(12):
h = 1;
break;
default:
h += 1;
break;
}
}
// override with current values if applicable
if(v.length == 7){
h = parseInt(v.substr(0,2));
m = parseInt(v.substr(3,2));
p = v.substr(5);
}
// build the new DOM objects
var output = '';
output += '<select id="h_' + i + '" class="h timepicker">';
for(hr in hrs){
output += '<option value="' + hrs[hr] + '"';
if(parseInt(hrs[hr]) == h) output += ' selected';
output += '>' + hrs[hr] + '</option>';
}
output += '</select>';
output += '<select id="m_' + i + '" class="m timepicker">';
for(mn in mins){
output += '<option value="' + mins[mn] + '"';
if(parseInt(mins[mn]) == m) output += ' selected';
output += '>' + mins[mn] + '</option>';
}
output += '</select>';
output += '<select id="p_' + i + '" class="p timepicker">';
for(pp in ap){
output += '<option value="' + ap[pp] + '"';
if(ap[pp] == p) output += ' selected';
output += '>' + ap[pp] + '</option>';
}
output += '</select>';
// hide original input and append new replacement inputs
$(this).attr('type','hidden').after(output);
});
$('select.timepicker').change(function(){
var i = this.id.substr(2);
var h = $('#h_' + i).val();
var m = $('#m_' + i).val();
var p = $('#p_' + i).val();
var v = h + ':' + m + p;
$('#' + i).val(v);
});
return this;
};
})(jQuery);
$(document).ready(function() {
$('.timepicker').timepicker();
});
/* SVN: $Id: jquery.timepicker.js 456 2007-07-16 19:09:57Z Jason Huck $ */
actiont.php
<?php
echo $_POST["timepicker"];
?>
Easiest solution would be to trigger change event once plugin is initialized:
$(document).ready(function() {
$('.timepicker').timepicker();
$('select.timepicker').change();
});
I have a code not very professional but it does what i want :). The code is basically doing if shop open count for how long if closed count how long left form opening. Now i wanted to style it with jQuery Countdown but i cant find any to just count hours,minutes, maybe seconds. I was trying UNIX countdowns but dunno what i`m doing wrong. I would like to ask you fellow citizens of Stackoverflow to help me out with this.
This is my code ( Just don`t be haters :) )
date_default_timezone_set('Greenwich'); //Fixes my server location
$openingtime = strtotime('06:00'); //Opening time
$closingtime = strtotime('23:10'); //Closing time
$timenow = strtotime('now'); //Current Server Time
$twentyfourhours = "24:00"; //Hours in a day
//echo date('G:i', $openingtime); //Just texting
//echo date('G:i', $closingtime);
//echo date('H:i', $timenow);
//echo $twentyfourhours;// Testing ends here
$openingin = $twentyfourhours - $timenow + $openingtime; //24:00 - 23:20 + 6:00 = How long left for opening
$closingdown = $closingtime - $timenow; //23:10 - 23:20 How long left to close
//If current time value is bigger then closing time then display when the shop will re-open again
if (date('H:i', $timenow) > date('H:i', $closingtime))
{
echo "The shop will be open in ".date('H:i', $openingin)." hours";
}
//If current time value is lower then closing time then display how long the shop will stay open
elseif (date('H:i', $timenow) < date('H:i', $closingtime))
{
echo "The shop will be open for ".date('H:i', $closingdown)." hours";
}
Ok i have managed to found one but now if you will go to My Testing Ground You will notice that the seconds instead of starting countdown from 60 they start from 00,99,98,97,97 and all the way down :( dunno why its happening im attaching JS code
var flipCounter = function(d, options){
// Default values
var defaults = {
value: 0,
inc: 1,
pace: 1000,
auto: true,
tFH: 39,
bFH: 64,
fW: 53,
bOffset: 390
};
var o = options || {},
doc = window.document,
divId = typeof d !== 'undefined' && d !== '' ? d : 'flip-counter',
div = doc.getElementById(divId);
for (var opt in defaults) o[opt] = (opt in o) ? o[opt] : defaults[opt];
var digitsOld = [], digitsNew = [], subStart, subEnd, x, y, nextCount = null, newDigit, newComma,
best = {
q: null,
pace: 0,
inc: 0
};
/**
* Sets the value of the counter and animates the digits to new value.
*
* Example: myCounter.setValue(500); would set the value of the counter to 500,
* no matter what value it was previously.
*
* #param {int} n
* New counter value
*/
this.setValue = function(n){
if (isNumber(n)){
x = o.value;
y = n;
o.value = n;
digitCheck(x,y);
}
return this;
};
/**
* Sets the increment for the counter. Does NOT animate digits.
*/
this.setIncrement = function(n){
o.inc = isNumber(n) ? n : defaults.inc;
return this;
};
/**
* Sets the pace of the counter. Only affects counter when auto == true.
*
* #param {int} n
* New pace for counter in milliseconds
*/
this.setPace = function(n){
o.pace = isNumber(n) ? n : defaults.pace;
return this;
};
/**
* Sets counter to auto-incrememnt (true) or not (false).
*
* #param {bool} a
* Should counter auto-increment, true or false
*/
this.setAuto = function(a){
if (a && ! o.atuo){
o.auto = true;
doCount();
}
if (! a && o.auto){
if (nextCount) clearNext();
o.auto = false;
}
return this;
};
/**
* Increments counter by one animation based on set 'inc' value.
*/
this.step = function(){
if (! o.auto) doCount();
return this;
};
/**
* Adds a number to the counter value, not affecting the 'inc' or 'pace' of the counter.
*
* #param {int} n
* Number to add to counter value
*/
this.add = function(n){
if (isNumber(n)){
x = o.value;
o.value += n;
y = o.value;
digitCheck(x,y);
}
return this;
};
/**
* Subtracts a number from the counter value, not affecting the 'inc' or 'pace' of the counter.
*
* #param {int} n
* Number to subtract from counter value
*/
this.subtract = function(n){
if (isNumber(n)){
x = o.value;
o.value -= n;
if (o.value >= 0){
y = o.value;
}
else{
y = "0";
o.value = 0;
}
digitCheck(x,y);
}
return this;
};
/**
* Increments counter to given value, animating by current pace and increment.
*
* #param {int} n
* Number to increment to
* #param {int} t (optional)
* Time duration in seconds - makes increment a 'smart' increment
* #param {int} p (optional)
* Desired pace for counter if 'smart' increment
*/
this.incrementTo = function(n, t, p){
if (nextCount) clearNext();
// Smart increment
if (typeof t != 'undefined'){
var time = isNumber(t) ? t * 1000 : 10000,
pace = typeof p != 'undefined' && isNumber(p) ? p : o.pace,
diff = typeof n != 'undefined' && isNumber(n) ? n - o.value : 0,
cycles, inc, check, i = 0;
best.q = null;
// Initial best guess
pace = (time / diff > pace) ? Math.round((time / diff) / 10) * 10 : pace;
cycles = Math.floor(time / pace);
inc = Math.floor(diff / cycles);
check = checkSmartValues(diff, cycles, inc, pace, time);
if (diff > 0){
while (check.result === false && i < 100){
pace += 10;
cycles = Math.floor(time / pace);
inc = Math.floor(diff / cycles);
check = checkSmartValues(diff, cycles, inc, pace, time);
i++;
}
if (i == 100){
// Could not find optimal settings, use best found so far
o.inc = best.inc;
o.pace = best.pace;
}
else{
// Optimal settings found, use those
o.inc = inc;
o.pace = pace;
}
doIncrement(n, true, cycles);
}
}
// Regular increment
else{
doIncrement(n);
}
}
/**
* Gets current value of counter.
*/
this.getValue = function(){
return o.value;
}
/**
* Stops all running increments.
*/
this.stop = function(){
if (nextCount) clearNext();
return this;
}
//---------------------------------------------------------------------------//
function doCount(){
x = o.value;
o.value += o.inc;
y = o.value;
digitCheck(x,y);
if (o.auto === true) nextCount = setTimeout(doCount, o.pace);
}
function doIncrement(n, s, c){
var val = o.value,
smart = (typeof s == 'undefined') ? false : s,
cycles = (typeof c == 'undefined') ? 1 : c;
if (smart === true) cycles--;
if (val != n){
x = o.value,
o.auto = true;
if (val + o.inc <= n && cycles != 0) val += o.inc
else val = n;
o.value = val;
y = o.value;
digitCheck(x,y);
nextCount = setTimeout(function(){doIncrement(n, smart, cycles)}, o.pace);
}
else o.auto = false;
}
function digitCheck(x,y){
digitsOld = splitToArray(x);
digitsNew = splitToArray(y);
var diff,
xlen = digitsOld.length,
ylen = digitsNew.length;
if (ylen > xlen){
diff = ylen - xlen;
while (diff > 0){
addDigit(ylen - diff + 1, digitsNew[ylen - diff]);
diff--;
}
}
if (ylen < xlen){
diff = xlen - ylen;
while (diff > 0){
removeDigit(xlen - diff);
diff--;
}
}
for (var i = 0; i < xlen; i++){
if (digitsNew[i] != digitsOld[i]){
animateDigit(i, digitsOld[i], digitsNew[i]);
}
}
}
function animateDigit(n, oldDigit, newDigit){
var speed, step = 0, w, a,
bp = [
'-' + o.fW + 'px -' + (oldDigit * o.tFH) + 'px',
(o.fW * -2) + 'px -' + (oldDigit * o.tFH) + 'px',
'0 -' + (newDigit * o.tFH) + 'px',
'-' + o.fW + 'px -' + (oldDigit * o.bFH + o.bOffset) + 'px',
(o.fW * -2) + 'px -' + (newDigit * o.bFH + o.bOffset) + 'px',
(o.fW * -3) + 'px -' + (newDigit * o.bFH + o.bOffset) + 'px',
'0 -' + (newDigit * o.bFH + o.bOffset) + 'px'
];
if (o.auto === true && o.pace <= 300){
switch (n){
case 0:
speed = o.pace/6;
break;
case 1:
speed = o.pace/5;
break;
case 2:
speed = o.pace/4;
break;
case 3:
speed = o.pace/3;
break;
default:
speed = o.pace/1.5;
break;
}
}
else{
speed = 80;
}
// Cap on slowest animation can go
speed = (speed > 80) ? 80 : speed;
function animate(){
if (step < 7){
w = step < 3 ? 't' : 'b';
a = doc.getElementById(divId + "_" + w + "_d" + n);
if (a) a.style.backgroundPosition = bp[step];
step++;
if (step != 3) setTimeout(animate, speed);
else animate();
}
}
animate();
}
// Creates array of digits for easier manipulation
function splitToArray(input){
return input.toString().split("").reverse();
}
// Adds new digit
function addDigit(len, digit){
var li = Number(len) - 1;
newDigit = doc.createElement("ul");
newDigit.className = 'cd';
newDigit.id = divId + '_d' + li;
newDigit.innerHTML = '<li class="t" id="' + divId + '_t_d' + li + '"></li><li class="b" id="' + divId + '_b_d' + li + '"></li>';
if (li % 2 == 0){
newComma = doc.createElement("ul");
newComma.className = 'cd';
newComma.innerHTML = '<li class="s"></li>';
div.insertBefore(newComma, div.firstChild);
}
div.insertBefore(newDigit, div.firstChild);
doc.getElementById(divId + "_t_d" + li).style.backgroundPosition = '0 -' + (digit * o.tFH) + 'px';
doc.getElementById(divId + "_b_d" + li).style.backgroundPosition = '0 -' + (digit * o.bFH + o.bOffset) + 'px';
}
// Removes digit
function removeDigit(id){
var remove = doc.getElementById(divId + "_d" + id);
div.removeChild(remove);
// Check for leading comma
var first = div.firstChild.firstChild;
if ((" " + first.className + " ").indexOf(" s ") > -1 ){
remove = first.parentNode;
div.removeChild(remove);
}
}
// Sets the correct digits on load
function initialDigitCheck(init){
// Creates the right number of digits
var initial = init.toString(),
count = initial.length,
bit = 1, i;
for (i = 0; i < count; i++){
newDigit = doc.createElement("ul");
newDigit.className = 'cd';
newDigit.id = divId + '_d' + i;
newDigit.innerHTML = newDigit.innerHTML = '<li class="t" id="' + divId + '_t_d' + i + '"></li><li class="b" id="' + divId + '_b_d' + i + '"></li>';
div.insertBefore(newDigit, div.firstChild);
if (bit != (count) && bit % 2 == 0){
newComma = doc.createElement("ul");
newComma.className = 'cd';
newComma.innerHTML = '<li class="s"></li>';
div.insertBefore(newComma, div.firstChild);
}
bit++;
}
// Sets them to the right number
var digits = splitToArray(initial);
for (i = 0; i < count; i++){
doc.getElementById(divId + "_t_d" + i).style.backgroundPosition = '0 -' + (digits[i] * o.tFH) + 'px';
doc.getElementById(divId + "_b_d" + i).style.backgroundPosition = '0 -' + (digits[i] * o.bFH + o.bOffset) + 'px';
}
// Do first animation
if (o.auto === true) nextCount = setTimeout(doCount, o.pace);
}
// Checks values for smart increment and creates debug text
function checkSmartValues(diff, cycles, inc, pace, time){
var r = {result: true}, q;
// Test conditions, all must pass to continue:
// 1: Unrounded inc value needs to be at least 1
r.cond1 = (diff / cycles >= 1) ? true : false;
// 2: Don't want to overshoot the target number
r.cond2 = (cycles * inc <= diff) ? true : false;
// 3: Want to be within 10 of the target number
r.cond3 = (Math.abs(cycles * inc - diff) <= 10) ? true : false;
// 4: Total time should be within 100ms of target time.
r.cond4 = (Math.abs(cycles * pace - time) <= 100) ? true : false;
// 5: Calculated time should not be over target time
r.cond5 = (cycles * pace <= time) ? true : false;
// Keep track of 'good enough' values in case can't find best one within 100 loops
if (r.cond1 && r.cond2 && r.cond4 && r.cond5){
q = Math.abs(diff - (cycles * inc)) + Math.abs(cycles * pace - time);
if (best.q === null) best.q = q;
if (q <= best.q){
best.pace = pace;
best.inc = inc;
}
}
for (var i = 1; i <= 5; i++){
if (r['cond' + i] === false){
r.result = false;
}
}
return r;
}
// http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric/1830844
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function clearNext(){
clearTimeout(nextCount);
nextCount = null;
}
// Start it up
initialDigitCheck(o.value);
};`
I've been working on getting a Coefficient of Variation equation ported from PHP to Javascript, but can't seem to get it working.
Original PHP script:
// define variables, strip spaces
$weights = $_POST['weights'];
// define coefficient of variation function
function cv($array){
$n = 0;
$mean = 0;
$M2 = 0;
foreach($array as $x){
if ($x != NULL AND $x != '') {
$n++;
$delta = $x - $mean;
$mean = $mean + $delta/$n;
$M2 = $M2 + $delta*($x - $mean);
$total = $total + $x;
}
}
return (((sqrt($M2/($n - 1))) / ($total/$n))*100);
}
$cv = (cv($weights));
This basically takes an array, and figures out the coefficient of variation for it. Now as I try to convert it to Javascript via some Jquery function:
var fields = $('#cvform').serializeArray();
var count = 0;
var num = 0;
var mean = 0;
var m2 = 0;
var total = 0;
var delta = 0;
jQuery.each(fields, function(i, field){
if (field.value > 0) {
num++;
delta=(field.value-mean);
mean=(mean+delta/num);
m2=(m2+delta*(field.value-mean));
total=(total+field.value);
};
});
var cov=(((Math.sqrt(m2/(num-1)))/(total/num))*100);
$("<span>Coefficient of Variation: " + cov + "</span>").appendTo('#cvdisplay');
While the javascript function outputs an answer, it is not correct. If I enter the values "3,3,2,3,3,4" the PHP script gives an output of 21.08, which is correct. The javascript function gives me the value of 0.0011418432035849642.
Can anyone point me to where the equations are differing?
You need to convert your array values to floats via parseFloat() (or integers, parseInt(), whatever suits you):
var fields = $('#cvform').serializeArray();
var count = 0;
var num = 0;
var mean = 0;
var m2 = 0;
var total = 0;
var delta = 0;
$.each(fields, function(i, field) {
alert(field.value);
if (parseFloat(field.value) > 0) {
num++;
delta = (parseFloat(field.value) - mean);
mean = (mean + delta / num);
m2 = (m2 + delta * (parseFloat(field.value) - mean));
total = (total + parseFloat(field.value));
}
});
var cov = (((Math.sqrt(m2 / (num - 1))) / (total / num)) * 100);
$("<span>Coefficient of Variation: " + cov + "</span>").appendTo('#cvdisplay');
The issue is the javascript line
total=(total+field.value); which results in 0332334 instead of 18 as expected. String concatenation is being applied instead of numeric addition.
You can fix this by parsing the integer value: total += parseInt(field.value);
function stDeviation(array){
var L= array.length,
mean= array.reduce(function(a, b){
return a+b;
})/L,
dev= array.map(function(itm){
var tem= itm-mean;
return tem*tem;
});
return Math.sqrt(dev.reduce(function(a, b){
return a+b;
})/L);
}
Math.mean= function(array){
return array.reduce(function(a, b){ return a+b; })/array.length;
}
Math.stDeviation=function(array){
var mean= Math.mean(array);
dev= array.map(function(itm){return (itm-mean)*(itm-mean); });
return Math.sqrt(dev.reduce(function(a, b){ return a+b; })/array.length);
}
var A2= [6.2, 5, 4.5, 6, 6, 6.9, 6.4, 7.5];
alert ('mean: '+Math.mean(A2)+'; deviation: '+Math.stDeviation(A2))
Here, I changed the code around a bit and got it to work. I basically isolated the segments a bit more. Made it more direct.
<?php
$weights = Array(3,3,2,3,3,4);
// define coefficient of variation function
function cv($array) {
$n = 0;
$mean = 0;
$M2 = 0;
$total = 0;
foreach($array as $x) {
if ( !empty($x) ) {
$n++;
$delta = $x - $mean;
$mean = $mean + $delta / $n;
$M2 = $M2 + $delta * ($x - $mean);
$total = $total + $x;
}
}
$sqrt = sqrt( $M2 / ($n - 1) );
$tn = $total / $n;
echo "Sqrt is $sqrt tn is $tn";
return ( $sqrt / $tn ) * 100;
}
$cv = cv($weights);
?>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var fields = Array(3,3,2,3,3,4);
var count = 0;
var n = 0;
var mean = 0;
var m2 = 0;
var total = 0;
var delta = 0;
jQuery.each(fields, function(i, field) {
//var x = field.value;
var x = 1 * field;
if (x > 0) {
n++;
delta = (x - mean);
mean = (mean + (delta / n));
m2 = (m2 + delta * (x - mean));
total = (total + x);
};
});
var sqrt = Math.sqrt(m2 / (n - 1));
var tn = total / n;
var cov = ((sqrt / tn) * 100);
console.log("Total is: "+ total);
console.log("Sqrt is " + sqrt + " tn is " + tn + " cov is " + cov);
$('#js').text("JS Output is: " + cov);
});
</script>
</head>
<body>
<div>
<div>PHP Output: <?=$cv;?></div>
<div id="js"></div>
</div>
</body>
</html>
Here's a direct translation of the function you provided. You have to pass in a javascript array of numbers, and it produces the result you're looking for (at least according to unit tests written in Node.js). You should to the type conversion (string-to-array) in another function to separate your concerns and make the code easier to reason about;
var CoV = function(ary) {
var mean = 0,
n = 0,
m2 = 0,
total = 0,
delta;
for(var i = 0, l = ary.length; i < l; i += 1) {
n += 1;
delta = ary[i] - mean;
mean = mean + delta / n;
m2 = m2 + delta * (ary[i] - mean)
total = total + ary[i]
}
console.log(mean);
console.log(m2);
console.log(total);
return ((Math.sqrt(m2/(i - 1))) / (total / i)) * 100;
};