how can i make simple news calendar on jQuery datepicker - php

I have code:
$(function() {
$('#datepicker').datepicker({
beforeShowDay: daysToMarkAndLink
});
});
function daysToMarkAndLink(date) {
.....(if daysToMarkAndLink matches){
......(link goes here and also highlight);
}
return [false];
}
<?
$sql = mysql_query("SELECT * FROM news");
while ($row = mysql_fetch_array($sql))
{
print $row["time_added"];
}
?>
i want to do something like, highlight the only days i have in database also and link them on my news page, filter by date_added.
i want a very simple news calendar on jQuery datepicker.
thanks

To implement this, you need to use a mix of beforeShowDay and onSelect like this:
<input type="textbox" id="mydate"></input>
<script>
//<![CDATA[
var dateArray = new Array();
// generate these from mysql. Replace the date by your date field
dateArray.push({date: new Date('2011/7/5'), link: 'http://mylink1.com'});
dateArray.push({date: new Date('2011/7/6'), link: 'http://mylink2.com'});
dateArray.push({date: new Date('2011/7/10'), link: 'http://mylink3.com'});
dateArray.push({date: new Date('2011/7/15'), link: 'http://mylink4.com'});
function formatDate(date) // we use function to convert date to a string we can debug
{
var mon = date.getMonth(); // 0-based
var day = date.getDate(); // 1-based
var yyy = date.getFullYear();
return (mon+1)+'/'+day+'/'+yyy;
}
$(function(){
$("#mydate").datepicker({
beforeShowDay: function(date) {
var bFound = false;
var sDate = formatDate(date);
for (var i = 0; i < dateArray.length; i++) {
var compDate = formatDate(dateArray[i].date);
if (sDate == compDate) {
bFound = true;
break;
}
}
return [bFound,'',''];
},
onSelect: function(dateText, inst) {
var sDate = formatDate(new Date(dateText));
for (var i = 0; i < dateArray.length; i++) {
var compDate = formatDate(dateArray[i].date);
if (sDate == compDate) {
document.location.href = dateArray[i].link;
break;
}
}
}
});
});
//]]>
</script>

Related

# mention script , make it work with div content editable [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
This is my at mention script , which works fine with a textarea . However now i want to use a div contenteditable instead for outputing Rich HTML inside . But i just cant figure out what changes do i need to implement in order to make this work perfectly with a content editable.
Please Help Me.
(function ($, undefined) {
$.fn.getCursorPosition = function () {
var el = $(this).get(0);
var pos = 0;
if ('selectionStart' in el) {
pos = el.selectionStart;
} else if ('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
return pos;
}
})(jQuery);
$.fn.setCursorPosition = function (pos) {
this.each(function (index, elem) {
if (elem.setSelectionRange) {
elem.setSelectionRange(pos, pos);
} else if (elem.createTextRange) {
var range = elem.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
});
return this;
};
$(document).ready(function (e) {
var selword;
var pcw;
var pcdw;
var start = /#/ig;
var word = /#(\w+)/ig;
var tagid = new Array();
$("#sparktext").click(function () {
var content = $(this).val();
var ty = $("#sparktext").getCursorPosition();
var firsts = content.substring(0, ty);
var lasts = content.substring(ty);
var faryw = firsts.split(" ");
var falw = faryw.length;
var lastw = faryw[falw - 1];
var laryw = lasts.split(" ");
var firstw = laryw[0];
selword = lastw + firstw;
var lenlastw = lastw.length;
var lenfirstw = firstw.length;
lenlastw = lenlastw - 1;
pcw = ty - lenlastw;
pcdw = ty + lenfirstw;
var fpcw = pcw - 1;
var fstr = content.substring(0, fpcw);
var lstr = content.substring(pcdw);
var go = selword.match(start);
var name = selword.match(word);
if (go == null) {
$("#display").hide();
$("#msgbox").hide();
}
});
$("#sparktext").keyup(function () {
var content = $(this).val();
var ty = $("#sparktext").getCursorPosition();
var firsts = content.substring(0, ty);
var lasts = content.substring(ty);
var faryw = firsts.split(" ");
var falw = faryw.length;
var lastw = faryw[falw - 1];
var laryw = lasts.split(" ");
var firstw = laryw[0];
selword = lastw + firstw;
var lenlastw = lastw.length;
var lenfirstw = firstw.length;
lenlastw = lenlastw - 1;
pcw = ty - lenlastw;
pcdw = ty + lenfirstw;
var go = selword.match(start);
var name = selword.match(word);
var dataString = 'searchword=' + name;
if (go == null) {
$("#display").hide();
$("#msgbox").hide();
}
if (go.length > 0) {
$.ajax({
type: "POST",
url: "http://localhost/PHP/Konnect/atmention.php",
data: dataString,
cache: false,
success: function (html) {
$("#display").html(html).show();
}
});
}
return false;
});
$(document).on("click", ".addname", function () {
var username = $(this).attr('title');
var old = $("#sparktext").val();
var musername = "#" + username;
var fpcw = pcw - 1;
var fstr = old.substring(0, fpcw);
var lstr = old.substring(pcdw);
if (lstr == "") {
var content = fstr + musername + " " + lstr;
} else {
var content = fstr + musername + lstr;
}
$("#sparktext").val(content);
$("#display").hide();
var curcont = content.length;
$("#sparktext").focus().setCursorPosition(curcont);
$("#msgbox").hide();
});
});
Here the id of the content editable is #sparktext .Thank You
Well i finally fixed it , for anyone who wants to use this feel free to do so
function getCaretPosition(editableDiv) {
var caretPos = 0,
sel, range;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0);
if (range.commonAncestorContainer.parentNode == editableDiv) {
caretPos = range.endOffset;
}
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
if (range.parentElement() == editableDiv) {
var tempEl = document.createElement("span");
editableDiv.insertBefore(tempEl, editableDiv.firstChild);
var tempRange = range.duplicate();
tempRange.moveToElementText(tempEl);
tempRange.setEndPoint("EndToEnd", range);
caretPos = tempRange.text.length;
}
}
return caretPos;
}
function setCaretPos(el, sPos)
{
/*range = document.createRange();
range.setStart(el.firstChild, sPos);
range.setEnd (el.firstChild, sPos);*/
var charIndex = 0, range = document.createRange();
range.setStart(el, 0);
range.collapse(true);
var nodeStack = [el], node, foundStart = false, stop = false;
while (!stop && (node = nodeStack.pop())) {
if (node.nodeType == 3) {
var nextCharIndex = charIndex + node.length;
if (!foundStart && sPos >= charIndex && sPos <= nextCharIndex) {
range.setStart(node, sPos - charIndex);
foundStart = true;
}
if (foundStart && sPos >= charIndex && sPos <= nextCharIndex) {
range.setEnd(node, sPos - charIndex);
stop = true;
}
charIndex = nextCharIndex;
} else {
var i = node.childNodes.length;
while (i--) {
nodeStack.push(node.childNodes[i]);
}
}
}
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
$(document).ready(function(e){
var selword;
var pcw;
var pcdw;
var start=/#/ig;
var word=/#(\w+)/ig;
var tagid = new Array();
$("#sparktext").click(function(){
var content=$(this).text();
var ty = getCaretPosition(this);
var firsts=content.substring(0,ty);
var lasts=content.substring(ty);
var faryw=firsts.split(" ");
var falw=faryw.length;
var lastw=faryw[falw-1];
var laryw=lasts.split(" ");
var firstw=laryw[0];
selword=lastw+firstw;
var lenlastw=lastw.length;
var lenfirstw=firstw.length;
lenlastw=lenlastw-1;
pcw=ty-lenlastw;
pcdw=ty+lenfirstw;
var fpcw=pcw-1;
var fstr=content.substring(0,fpcw);
var lstr=content.substring(pcdw);
var go = selword.match(start);
var name= selword.match(word);
if(go==null)
{
$("#display").hide();
$("#msgbox").hide();
}
});
$("#sparktext").keyup(function()
{
var content=$(this).text();
var ty = getCaretPosition(this);
var firsts=content.substring(0,ty);
var lasts=content.substring(ty);
var faryw=firsts.split(" ");
var falw=faryw.length;
var lastw=faryw[falw-1];
var laryw=lasts.split(" ");
var firstw=laryw[0];
selword=lastw+firstw;
var lenlastw=lastw.length;
var lenfirstw=firstw.length;
lenlastw=lenlastw-1;
pcw=ty-lenlastw;
pcdw=ty+lenfirstw;
var go = selword.match(start);
var name= selword.match(word);
var dataString = 'searchword='+ name;
if(go==null)
{
$("#display").hide();
$("#msgbox").hide();
}
if(go.length>0)
{
$.ajax({
type: "POST",
url: "AJAX FILE GOES HERE",
data: dataString,
cache: false,
success: function(html)
{
$("#display").html(html).show();
}
});
}
return false;
});
$(document).on("click",".addname",function(){
var username=$(this).attr('title');
var old=$("#sparktext").text();
var musername="#"+username+" ";
var fpcw=pcw-1;
var fstr=old.substring(0,fpcw);
var lstr=old.substring(pcdw);
if(lstr=="")
{
var content = fstr+musername+""+lstr;
}
else
{
var content = fstr+musername+"---"+lstr+"---";
}
$("#sparktext").html(content+" ");
$("#display").hide();
var curcont=parseInt(content.length);
setCaretPos(document.getElementById("sparktext"),curcont);
$("#msgbox").hide();
});
});

PHP with javascript code, live clock

Hey I would to create a live clock to put it on my website. So I wrote a simple php with JavaScript code for that, here is it:
<?php
Function d1() {
$time1 = Time();
$date1 = date("h:i:s A",$time1);
echo $date1;
}
?>
<script type="text/javascript">
window.onload = startInterval;
function startInterval() {
setInterval("startTime();",1000);
}
function startTime() {
document.getElementById('qwe').innerHTML = '<?php d1();?>';
}
</script>
<div id="qwe">test</div>
When run this code the output like "2:40:17 PM", the div refreshed every second but the problem is the time never changed.
Get the initial time you want to start your clock with from PHP:
<script>
var now = new Date(<?php echo time() * 1000 ?>);
function startInterval(){
setInterval('updateTime();', 1000);
}
startInterval();//start it right away
function updateTime(){
var nowMS = now.getTime();
nowMS += 1000;
now.setTime(nowMS);
var clock = document.getElementById('qwe');
if(clock){
clock.innerHTML = now.toTimeString();//adjust to suit
}
}
</script>
For formatting the date there's a zillion options (MDN Date API: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date)
<script type="text/javascript">
function timedMsg()
{
var t=setInterval("change_time();",1000);
}
function change_time()
{
var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
var curr_sec = d.getSeconds();
if(curr_hour > 12)
curr_hour = curr_hour - 12;
document.getElementById('Hour').innerHTML =curr_hour+':';
document.getElementById('Minut').innerHTML=curr_min+':';
document.getElementById('Second').innerHTML=curr_sec;
}
timedMsg();
</script>
<table>
<tr>
<td>Current time is :</td>
<td id="Hour" style="color:green;font-size:large;"></td>
<td id="Minut" style="color:green;font-size:x-large;"></td>
<td id="Second" style="color:red;font-size:xx-large;"></td>
<tr>
</table>
use this way to display time........
enjoy the above script
You can use ajax to refresh the time:
Example:
<?php
if(#$_GET["action"]=="getTime"){
$time1 = Time();
$date1 = date("h:i:s A",$time1);
echo $date1; // time output for ajax request
die();
}
?>
<div id="qwe">test</div>
<script type="text/javascript">
window.onload = startInterval;
function startInterval() {
setInterval("startTime();",1000);
}
function startTime() {
AX = new ajaxObject("?action=getTime", showTime)
AX.update(); // start Ajax Request
}
// CallBack
function showTime( data ){
document.getElementById('qwe').innerHTML = data;
}
</script>
<script type="text/javascript">
// Ajax Object - Constructor
function ajaxObject(url, callbackFunction) {
var that=this;
this.updating = false;
this.abort = function() {
if (that.updating) {
that.updating=false;
that.AJAX.abort();
that.AJAX=null;
}
};
this.update =
function(passData,postMethod) {
if (that.updating) { return false; }
that.AJAX = null;
if (window.XMLHttpRequest) {
that.AJAX=new XMLHttpRequest();
}else{
that.AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (that.AJAX==null) {
return false;
}else{
that.AJAX.onreadystatechange = function() {
if (that.AJAX.readyState==4) {
that.updating=false;
that.callback( that.AJAX.responseText, that.AJAX.status, that.AJAX.responseXML, that.AJAX.getAllResponseHeaders() );
that.AJAX=null;
}
};
that.updating = new Date();
if (/post/i.test(postMethod)) {
var uri=urlCall+(/\?/i.test(urlCall)?'&':'?')+'timestamp='+that.updating.getTime();
that.AJAX.open("POST", uri, true);
that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
that.AJAX.setRequestHeader("Content-Length", passData.length);
that.AJAX.send(passData);
}else{
var uri=urlCall+(/\?/i.test(urlCall)?'&':'?')+passData+'&timestamp='+(that.updating.getTime());
that.AJAX.open("GET", uri, true);
that.AJAX.send(null);
}
return true;
}
};
var urlCall = url;
this.callback = callbackFunction || function (){};
}
</script>

How to call php script via Json and return array of days to be disable on the Datepicker

In the following example, I need to know how to call, via json, a php script that reads a MySql table, and return the array with the $myBadDates to be disable:
$(function() {
$( "#pickdate" ).datepicker({
dateFormat: 'dd MM yy',
beforeShowDay: checkAvailability
});
})
var $myBadDates = new Array("10 October 2010","21 October 2010","12 November 2010");
function checkAvailability(mydate){
var $return=true;
var $returnclass ="available";
$checkdate = $.datepicker.formatDate('dd MM yy', mydate);
for(var i = 0; i < $myBadDates.length; i++)
{
if($myBadDates[i] == $checkdate)
{
$return = false;
$returnclass= "unavailable";
}
}
return [$return,$returnclass];
}
Here is my php script : close_dates.php, how do I send the json ajax request and get the array result into the checkAvailability Function : >
include 'panel/db.php';
$dates_closed = array();
/// Query Dates Closed ///
$query = "SELECT dates from closed_dates order by dates ";
$result = mysql_query($query);
while($row=mysql_fetch_array($result)) {
$days = $row['dates'];
array_push($date_closed,$days);
}
echo json_encode($date_closed);
?>

How to get total value on dynamic value?

I have form like this :
<input type='hidden' name='seq' id='idseq' value='1' />
<div id='add_field' class='locbutton'><a href='#' title='Add'>Add</a></div>
<div id='remove_field' class='locbutton2'><a href='#' title='Delete'>Delete</a></div>
<div id="idcover">
1.<br />
<div class="group">
<div class="satu"><input type='text' name='score[1][]' id='score[1][]'></div>
<div class="dua"><input type='text' name='weight[1][]' id='weight[1][]'> %</div>
<div class="tiga"><input type='text' name='weightscore[1][]' id='weightscore[1][]'
disabled></div>
</div>
</div>
<br /><br />
<div id='idtotalcover' class='totalcover'>
Total <div class='total'><input type='text' name='total' id='idtotal' disabled /></div>
</div>
This is the jquery script:
<script type="text/javascript">
$(document).ready(
function ()
{
$("input[id^=score],input[id^=weight]").bind("keyup", recalc);
recalc();
var counter = $("#idseq").val();
$("#add_field").click(function ()
{
counter++;
$.ajax({
url: 'addinput.php',
dataType: "html",
data: "count="+counter,
success: function(data)
{
$('#idcover').append(data);
$('.dua input').keyup(function()
{
var $duaInput = $(this);
var weight=$duaInput.val();
var score=$duaInput.closest(".group").find('.satu input').val();
$.ajax({
url: "cekweightscore.php",
data: "score="+score+"&weight="+weight,
success:
function(data)
{
$duaInput.closest(".group").find('.tiga input').val(data);
}//success
});//ajax
});
}//success
});//ajax
});
});
function recalc()
{
var a=$("input[id^=score]");
var b=$("input[id^=weight]");
$("[id^=weightscore]").calc("(score * weight)/100",{score: a,weight: b},
function (s)
{
return s.toFixed(2);
},
function ($this){
//function($("[id^=weightscore]")){
// sum the total of the $("[id^=total_item]") selector
//alert($this);
//var sum = $this.sum();
var sum=$this.sum();
$("#idtotal").val(sum.toFixed(2));
}
);
}
</script>
This is the php code:
<?
$count=$_GET['count'];
echo"
<br>
$count
<div class='group' >
<div class='satu'>
<input type='text' name='score[$count][]' id='score[$count][]'>
</div>
<div class='dua'>
<input type='text' name='weight[$count][]' id='weight[$count][]'> %
</div>
<div class='tiga'>
<input type='text' name='weightscore[$count][]' id='weightscore[$count][]' disabled>
</div>
</div>";
?>
When I click the Add button, i cant get value on new form so that the new form cannot be calculated. What can i do to get total value on dynamic value ?
I remember reading this exact same question yesterday and I still have no idea of what you're trying to do.
Why are you adding inputs through AJAX instead of creating them in Javascript from the beginning? AJAX calls are expensive and are recommended to be used when you need to update/retrieve values from the server.
Why are you trying to do your calculations on the server side anyway? If you're dealing with dynamic input, you should be doing the calculations client side, then update the server when you're done.
Why do you use obscure name/id attribute values?
Anyway,
I created this example, it contains two different solutions, one with a ul and a table. Hopefully, the example matches what you're trying to do and might give you some insight.
I use a timer to update simulated server data. The timer is set to the variable update_wait. The other dynamic calculations are done client side.
I'll post the Javascript code as well, in case you don't like to fiddle
Example | Javascript
var update_server_timer = null,
update_wait = 1000; //ms
var decimals = 3;
/**********************
List solution
**********************/
function CreateListRow(){
var eLi = document.createElement("li"),
eScore = document.createElement("div"),
eWeight = document.createElement("div"),
eWeightScore = document.createElement("div");
var next_id = $("#cover li:not(.total)").length + 1
eScore.className = "score";
eWeight.className = "weight";
eWeightScore.className = "weightscore";
//Score element
var eScoreInput = document.createElement("input");
eScoreInput.type = "text";
eScoreInput.name = "score_"+next_id;
eScoreInput.id = "score_"+next_id;
eScore.appendChild(eScoreInput);
//Weight element
var eWeightInput = document.createElement("input");
eWeightInput.type = "text";
eWeightInput.name = "weight_"+next_id;
eWeightInput.id = "weight_"+next_id;
var eWeightPerc = document.createElement("div");
eWeightPerc.className = "extra";
eWeightPerc.innerHTML = "%";
eWeight.appendChild(eWeightInput);
eWeight.appendChild(eWeightPerc);
//Weightscore element
var eWeightScoreInput = document.createElement("input");
eWeightScoreInput.type = "text";
eWeightScoreInput.name = "weight_"+next_id;
eWeightScoreInput.id = "weight_"+next_id;
eWeightScore.appendChild(eWeightScoreInput);
$(eScore).keyup(function(){
CalculateListRow($(this).closest("li"));
});
$(eWeight).keyup(function(){
CalculateListRow($(this).closest("li"));
});
//item element
eLi.appendChild(eScore);
eLi.appendChild(eWeight);
eLi.appendChild(eWeightScore);
return eLi;
}
function CalculateListRowTotal(){
var fTotal = 0;
$("#cover li:not(.total) div:nth-child(3) input").each(function(){
var fVal = parseFloat($(this).val());
if(isNaN(fVal)) fVal = 0;
fTotal += fVal;
});
fTotal = parseFloat(fTotal.toFixed(decimals));
$("#cover li.total div input").val(fTotal);
//Update server variables here
RestartUpdateServerTimer();
}
function CalculateListRow($Li){
var fScore = parseFloat($("div.score input", $Li).val()),
fWeight = parseFloat($("div.weight input", $Li).val())/100,
fRes = (fScore*fWeight);
if(isNaN(fRes)) fRes = 0.00;
$("div.weightscore input", $Li).val(parseFloat(fRes.toFixed(decimals)));
CalculateListRowTotal();
}
$("#cover li div.weight input, #cover li div.score input").keyup(function(){
CalculateListRow($(this).closest("li"));
});
function AddListRow(){
$("#cover li.total").before(CreateListRow());
RestartUpdateServerTimer();
}
function RemoveListRow(){
$("#cover li.total").prev().remove();
CalculateListRowTotal();
}
$(".left_container .menu .add").click(function(){ AddListRow(); });
$(".left_container .menu .rem").click(function(){ RemoveListRow(); });
/**********************
Table solution
**********************/
function CreateTableRow(){
var eTr = document.createElement("tr"),
eTds = [document.createElement("td"),
document.createElement("td"),
document.createElement("td")];
var next_id = $("#cover2 tbody tr").length + 1;
$(eTds[0]).append(function(){
var eInput = document.createElement("input");
eInput.type = "text";
eInput.name = eInput.id = "score_"+next_id;
$(eInput).keyup(function(){
CalculateTableRow($(this).closest("tr"));
});
return eInput;
});
$(eTds[1]).append(function(){
var eRelativeFix = document.createElement("div"),
eInput = document.createElement("input"),
eExtra = document.createElement("div");
eRelativeFix.className = "relative_fix";
eInput.type = "text";
eInput.name = eInput.id = "weight_"+next_id;
eExtra.innerHTML = "%";
eExtra.className = "extra";
eRelativeFix.appendChild(eInput);
eRelativeFix.appendChild(eExtra);
$(eInput).keyup(function(){
CalculateTableRow($(this).closest("tr"));
});
return eRelativeFix;
});
$(eTds[2]).append(function(){
var eInput = document.createElement("input");
eInput.type = "text";
eInput.name = eInput.id = "weightscore_"+next_id;
return eInput;
});
for(i = 0; i < eTds.length; i++){
eTr.appendChild(eTds[i]);
}
return eTr;
}
function CalculateTableRowTotals(){
var $rows = $("#cover2 tbody tr"),
$totals = $("#cover2 tfoot tr th");
var fTotal = [];
//Each row
$rows.each(function(){
var $columns = $("td", this);
//Each column
$columns.each(function(i, e){
var fVal = parseFloat($("input", e).val());
if(isNaN(fVal)) fVal = 0;
if(isNaN(fTotal[i])) fTotal[i] = 0;
fTotal[i] += fVal;
});
});
for(i = 0; i < fTotal.length; i++){
fTotal[i] = parseFloat(fTotal[i].toFixed(decimals));
}
fTotal[1] = (fTotal[2]/fTotal[0]*100).toFixed(decimals)+"%";
fTotal[2] = parseFloat(fTotal[2].toFixed(decimals));
$totals.each(function(i, e){
$(this).text(fTotal[i]);
});
//Update server variables here
RestartUpdateServerTimer();
}
function CalculateTableRow($Tr){
var fScore = parseFloat($("td:nth-child(1) input", $Tr).val()),
fWeight = parseFloat($("td:nth-child(2) input", $Tr).val())/100,
fRes = (fScore*fWeight);
if(isNaN(fRes)) fRes = 0.00;
$("td:nth-child(3) input", $Tr).val(parseFloat(fRes.toFixed(decimals)));
CalculateTableRowTotals();
}
function AddTableRow(){
if($("#cover2 tbody tr").length == 0){
$("#cover2 tbody").append(CreateTableRow());
}else{
$("#cover2 tbody tr:last-child").after(CreateTableRow());
}
RestartUpdateServerTimer();
}
function RemoveTableRow(){
$("#cover2 tbody tr:last-child").remove();
CalculateTableRowTotals();
}
$(".right_container .menu .add").click(function(){ AddTableRow(); });
$(".right_container .menu .rem").click(function(){ RemoveTableRow(); });
$("#cover2 tbody tr td:nth-child(1) input, #cover2 tbody tr td:nth-child(2) input").keyup(function(){
CalculateTableRow($(this).closest("tr"));
});
/**********************
Server data
- Simulates the data on the server,
- whether it be in a SQL server or session data
**********************/
var ServerData = {
List: {
Count: 3,
Total: 5.50
},
Table: {
Count: 3,
Totals: [65, 8.46, 5.50]
}
};
function UpdateServerData(){
//List
var ListCount = $("#cover li:not(.total)").length,
ListTotal = $("#cover li.total input").val();
//Table
var TableCount = $("#cover2 tbody tr").length,
TableTotals = [];
$("#cover2 tfoot th").each(function(i, e){
TableTotals[i] = parseFloat($(this).text());
});
var data = {
json: JSON.stringify({
List: {
Count: ListCount,
Total: ListTotal
},
Table: {
Count: TableCount,
Totals: TableTotals
}
})
}
//Update
$.ajax({
url: "/echo/json/",
data: data,
dataType: "json",
type:"POST",
success: function(response){
ServerData.List = response.List;
ServerData.Table = response.Table;
var displist = "Server data<h1>List</h1><ul><li>Count: "+ServerData.List.Count+"</li><li>Total: "+ServerData.List.Total+"</li></ul>",
disptable = "<h1>Table</h1><ul><li>Count: "+ServerData.Table.Count+"</li>";
for(i=0; i<ServerData.Table.Totals.length; i++)
disptable += "<li>Total "+i+": "+ServerData.Table.Totals[i]+"</li>";
disptable += "</ul>";
$("#server_data").html(displist+"<br />"+disptable).effect("highlight");
}
});
}
function RestartUpdateServerTimer(){
if(update_server_timer != null) clearTimeout(update_server_timer);
update_server_timer = setTimeout(function(){
UpdateServerData()
}, update_wait);
}
UpdateServerData();
Update
Since you have a hard time grasping the concept, here's a copy paste solution that will work for you without having to use AJAX. I would like to point out that your HTML markup and general coding is a total mess...
Example | Code
<script type="text/javascript">
$(document).ready(function(){
function CreateInput(){
var $group = $("<div>"),
$score = $("<div>"),
$weight = $("<div>"),
$weightscore = $("<div>");
var group_count = $("div.group").length+1;
$group.addClass("group");
$score.addClass("satu");
$weight.addClass("dua");
$weightscore.addClass("tiga");
var $input_score = $("<input>"),
$input_weight = $("<input>"),
$input_weightscore = $("<input>")
$input_score
.attr("name", "score["+group_count+"][]")
.attr("type", "text")
.attr("id", "score["+group_count+"][]");
$input_weight
.attr("name", "weight["+group_count+"][]")
.attr("type", "text")
.attr("id", "weight["+group_count+"][]");
$input_weightscore
.attr("name", "weightscore["+group_count+"][]")
.attr("type", "text")
.attr("id", "weightscore["+group_count+"][]")
.attr("disabled", true);
$input_score.keyup(function(){
CalculateGroup($(this).parents(".group"));
});
$input_weight.keyup(function(){
CalculateGroup($(this).parents(".group"));
});
$score.append($input_score);
$weight.append($input_weight);
$weightscore.append($input_weightscore);
$group.append($score)
.append($weight)
.append($weightscore);
return $group;
}
function CalculateGroup($group){
var fScore = parseFloat($(".satu input", $group).val()),
fWeight = parseFloat($(".dua input", $group).val()),
fWeightScore = parseFloat((fScore*(fWeight/100)).toFixed(2));
if(isNaN(fWeightScore)) fWeightScore = 0;
$(".tiga input", $group).val(fWeightScore);
CalculateTotal();
}
function CalculateTotal(){
var fWeightScoreTotal = 0;
$("#idcover div.group div.tiga input").each(function(){
var fTotal = parseFloat(parseFloat($(this).val()).toFixed(2));
if(isNaN(fTotal)) fTotal = 0;
fWeightScoreTotal += fTotal;
});
fWeightScoreTotal = parseFloat(fWeightScoreTotal.toFixed(2));
$("#idtotalcover div.total input").val(fWeightScoreTotal);
}
$(".satu input, .dua input").keyup(function(){
CalculateGroup($(this).parents(".group"));
});
$("#add_field a").click(function(e){
$("#idcover").append(CreateInput());
e.preventDefault();
});
$("#remove_field a").click(function(e){
$("#idcover div.group:last-child").remove();
CalculateTotal();
e.preventDefault();
});
});
</script>

change link background in jQuery datepicker

i have a script. jQuery datepicker with url's on database.
<script>
$(function() {
$('#datepicker').datepicker({
beforeShowDay: daysToMark,
onSelect: function(date,evt){
if (evt.currentMonth < 10){
evt.currentMonth = "0"+evt.currentMonth;
}
if (evt.currentDay < 10){
evt.currentDay = "0"+evt.currentDay;
}
daysToMark(evt.currentYear+"-"+evt.currentMonth+"-"+evt.currentDay);
date.dpDiv.find('.ui-datepicker-current-day a')
.css('background-color', '#000000');
}
});
});
<?
$dateArray = array();
$sql = mysql_query("SELECT *
FROM module_news
");
while ($row = mysql_fetch_array($sql)) {
array_push($dateArray,$row["tarigi"]);
}
?>
var js_array = new Array();
js_array = <?=json_encode($dateArray);?>;
var dates = js_array;
function daysToMark(evt) {
if($.inArray(evt, js_array) != -1 )
{
window.open("index.php?action=news_archive&date="+evt+"&lang=<?=$lang?>", "_self");
}
return [true, "", ""];
}
</script>
I have database date links in array, and i want to highlight links, so when i write news at 2011-07-08 on my calendar it 'll be linked but not highlighted, how can i change background color of linked dates?
thanks
In the daysToMark method you return return [true, "", ""]; as required by the beforeShowDay event.
The second position in that array hold a class that will be applied to the data. So if you add a class there return [true, "linked", ""]; and in you css code set a rule of
.linked .ui-state-default{
background-color:red;
background-image:none; /*this in case the them you use uses background images*/
}
it should do what you want..
demo at http://jsfiddle.net/gaby/S79fa/
replace this line
date.dpDiv.find('.ui-datepicker-current-day a')
.css('background-color', '#000000');
with below code
var atag = date.dpDiv.find('.ui-datepicker-current-day a');
atag.queue(function() {
atag.css("background-color", "black");
});
this may be helpful
Thanks.

Categories