<div id="newdiv"> </div> <div id="createblocks"> </div> <script>
//http://www.eugeniucozac.com/parser/parsethisxml.xml
jQuery(document).ready(function ($) {
var last_category_value = ""; var xml_url = "parsethisxml.xml";
$.ajax({
url: xml_url,
type: "GET",
dataType: "xml",
cache: false,
success: function (msg) {
$(msg).find('item').each(function (id, item) {
var id, title, status, category, content;
id = $(item).find('Id').text();
title = $(item).find('Title').text();
status = $(item).find('PublishingApproval').text();
category = $(item).find('Category').text();
content = $(item).find('Content').text();
var resulthtml = "";
var with_category_ = with_category();
var without_category_ = without_category();
if(category == last_category_value){
resulthtml = with_category_.append(without_category_);
category = "";
} else{
resulthtml = without_category_
last_category_value = category;
}
var eachsection = resulthtml.appendTo("#newdiv");
$(eachsection).each(function() {
$(this).show();
$(this).find('.q_weblinksprite_med').text(title);
$(this).find(".status").text(status);
$(this).find('.q_rt_rowcell-1-title').text(category);
});
});
function with_category(){
var container = $("<div>").attr('id', 'q_resultslist');
var boxlist = $("<div>").addClass("q_boxlist");
var rowcell2 = $("<div>").addClass("q_rt_rowcell2");
var dividerwide = $("<div>").addClass("q_dividerwide");
var grid_20 = $("<div>").addClass("grid-20 q_padright");
var category_title = $("<div>").addClass("q_rt_rowcell-1-title q_reducefont");
var with_category = container.appendTo("#createblocks");
boxlist.appendTo(container);
rowcell2.appendTo(boxlist);
dividerwide.appendTo(rowcell2);
grid_20.appendTo(rowcell2);
category_title.appendTo(grid_20);
return with_category;
}
function without_category(){
var rowcell2 = $("<div>").addClass("q_rt_rowcell2");
var grid_80 = $("<div>").addClass("grid-80 q_rt_rowcell-2 q_padleft q_add-margin-bottom");
var spriteindent = $("<div>").addClass("q_spriteindent-med");
var post_title = $("<div>").addClass("q_rt_rowcell-2-title");
var post_titlea = $("<a>").addClass("q_weblinksprite_med").attr("onclick", "spDialog()");
var prestatus = $("<div>").addClass("q_rt_rowcell-2-body q_spriteindent-lefttext");
var prestatus_second = $("<div>").addClass("q_rt_rowcell-2-body q_spriteindent-lefttext");
var clipline = $("<div>").addClass("q_clipline");
var readmore = $("<div>").addClass("q_readmore");
var readmorea = $("<a>").attr("onclick", "spDialog()");
var readmoreimg = $("<img>").attr("src", "/_layouts/15/images/edititem.gif?rev=23");
var statusem = $("<em>").text("Status:").append("<span class='status'>")
var without_category = grid_80.appendTo("#createblocks");
grid_80.appendTo(rowcell2);
spriteindent.appendTo(grid_80);
post_title.appendTo(spriteindent);
post_titlea.appendTo(post_title);
prestatus.appendTo(spriteindent);
prestatus.append(statusem);
prestatus_second.appendTo(spriteindent);
clipline.appendTo(prestatus_second);
readmore.appendTo(prestatus_second);
readmorea.appendTo(readmore);
readmoreimg.appendTo(readmorea);
return without_category;
}
},
error: function (msg) {
console.log("Error");
}
});
}); </script>
Hello! to all here! I have a code, and what I want just if you see my XML I ahve 3 posts which 2 of them has the same category, what I want if the posts has the same category just to show the category only on first post.
This part of code needs to work logicaly but it doesnt:
var resulthtml = "";
var with_category_ = with_category();
var without_category_ = without_category();
if(category == last_category_value){
resulthtml = with_category_.append(without_category_);
category = "";
} else{
resulthtml = without_category_
last_category_value = category;
}
but I think i made a few mistakes, thanks!
Related
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();
});
});
I'm trying to send a php form data via AJAX (without the refresh) and display data in new form. I echo query but it didnt work. On AJAX response it shows me getReportAj form on call.The code goes like this:
Javascript
function getReport()
{
var dataString = "grNo=" +$(".grNo").val();
$.ajax({
type: "GET",
url: "getReportAj.php",
data: dataString,
success:function(data)
{
$('#result').html(data);
}
});
}
getReportAj.php
<?php
include "include/config.inc.php";
if(!isset($_SESSION['s_activName']) && !isset($_SESSION['s_userType']) || isset($_SESSION['s_userType']) && $_SESSION['s_userType'] == 'Student') {
$_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
header("Location:checkLogin.php");
}
else {
if(isset($_REQUEST['submit'])) {
$selectReport = "SELECT * from gradeterm1
WHERE studentId = ".$_POST['studentId']."
AND termValue = 1
LEFT JOIN studentmaster ON studentmaster.studentId = gradeterm1.studentId";
$selectReportRes = mysql_query($selectReport);
if($reportRow = mysql_fetch_array($selectReportRes)); {
$eReadingPro = $reportRow['eReadingPro'];
$eReadingFlu = $reportRow['eReadingFlu'];
$eReadingCom = $reportRow['eReadingCom'];
$eWritingCre = $reportRow['eWritingCre'];
$eWritingHan = $reportRow['eWritingHan'];
$eWritingGra = $reportRow['eWritingGra'];
$eWritingSpe = $reportRow['eWritingSpe'];
$eWritingVoc = $reportRow['eWritingVoc'];
$ewSpeakinCon = $reportRow['ewSpeakinCon'];
$ewSpeakinRec = $reportRow['ewSpeakinRec'];
$ewSpeakinCla = $reportRow['ewSpeakinCla'];
$eListingComp = $reportRow['eListingComp'];
$eListingCon = $reportRow['eListingCon'];
$extraReading = $reportRow['extraReading'];
$activityPro = $reportRow['activityPro'];
$hiReadingPro = $reportRow['hiReadingPro'];
$hiReadingFlu = $reportRow['hiReadingFlu'];
$hiReadingCom = $reportRow['hiReadingCom'];
$hiWritingCre = $reportRow['hiWritingCre'];
$hiWritingHan = $reportRow['hiWritingHan'];
$hiWritingGra = $reportRow['hiWritingGra'];
$hiWritingSpe = $reportRow['hiWritingSpe'];
$hiWritingVoc = $reportRow['hiWritingVoc'];
$hiwSpeakinCon = $reportRow['hiwSpeakinCon'];
}
}
}
include("./bottom.php");
$smarty->display('getReportAj.tpl');
?>
<script>
function getReport()
{
var dataString = "grNo=" +$(".grNo").val();
$.ajax({
type: "GET",
url: "getReportAj.php",
data: dataString,
success:function(data)
{
$('#result').html(data);
console.log(data);
}
});
}
</script>
in success event.. put the console.log(data) then run the script and check in console.
Consider the following PHP Block. I want to output "name" to div #1 and "slog" to div #2
<?php
require_once 'db_conx.php';
$Result = mysql_query("SELECT * FROM profiles ORDER BY lastupdated desc limit 1") or die (mysql_error());
while($row = mysql_fetch_array($Result)){
$result = array();
$result['name'] = $row['name'];
$result['slog'] = $row['slog'];
echo json_encode($result);
}
mysql_close($con);
?>
Here's the ajax that just outputs json itself.
var get_fb = (function() {
var counter = 0;
var $buzfeed = $('#BuzFeed');
return function(){
$.ajax({
type: "POST",
url: "../php/TopBusinesses_Algoriththm.php"
}).done(function(feedback) {
counter += 1;
var $buzfeedresults = $("<div id='BuzFeedResult" + counter + "'></div>").addClass('flat-menu-button');
$buzfeedresults.text(feedback);
$buzfeed.append($buzfeedresults);
var $buzfeedDivs = $buzfeed.children('div');
if ($buzfeedDivs.length > 10) { $buzfeedDivs.last().remove(); }
setTimeout(get_fb, 1000);
})
};
})();
get_fb();
You can update the html/content of a DOM element with the following:
document.getElementById(name).innerHTML = "text";
So in this instance:
document.getElementById('#1').innerHTML = $yourNameContent;
document.getElementById('#2').innerHTML = $yourSlogContent;
First: move var counter = 0; outside from get_fb() function;
Second: Do not call get_fb(); explicitly, because (function(){...})(); already calls method after initialization.
Third: Why use POST method if there is not data to submit!
So, do this and have a try:
var counter = 0;
var $buzfeed = $('#BuzFeed');
var get_fb = (function() {
$.ajax({
type: "GET",
url: "../php/TopBusinesses_Algoriththm.php"
}).done(function(feedback) {
counter += 1;
var $buzfeedresults = $("<div id='BuzFeedResult" + counter + "'></div>").addClass('flat-menu-button');
$buzfeedresults.text(feedback);
$buzfeed.append($buzfeedresults);
var $buzfeedDivs = $buzfeed.children('div');
if ($buzfeedDivs.length > 10) { $buzfeedDivs.last().remove(); }
setTimeout(get_fb, 1000);
})
})();
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>
this was the delete link
<div class="artworkdelete">
Delete
</div>
apparently, when that link is clicked, the portal deletes the data automatically, i think it's an ajax thing because the page doesn't refresh. so i was ask to add a confirm pop up to ask the user to click yes or no if he wants to delete the data or not, and within the confirm box , it should mention the name of the data to be deleted like e.g
"are you sure you want to delete row_title ?"
here's the function of the deleteThisArtWork()
function deleteThisArtWork(artwork_id){
var artwork_id = artwork_id.split('_');
var cat_id=artwork_id[2];
artwork_id = artwork_id[1];
//$('#divStatus').html('processing request, please wait');
//$(".pleaseWait").dialog("open");
openLightBox();
$.ajax({
type: 'POST',
url: '<?php echo BASE_URL;?>ajax/ajax_methods_gallery.php',
data: 'deleteartwork=yes&artwork_id='+artwork_id+'&category_id='+cat_id,
success: function(msg){
//alert(msg);
msg = 'done';
var status=msg;
var deleted='';
if(status == 'done') {
var temp_lid = 'li_'+artwork_id+'_'+cat_id+'_';
//alert(counter);
for(var v=1;v<counter;v++){
var curid = tempIdArr[v];
curid = curid.split('#');
var curlid = curid[0];
if(temp_lid == curlid){
var del_aw_pos = curid[1];
break;
}
}
del_aw = temp_lid+'#'+del_aw_pos;
var i = 1;
var j =0;
var op = false;
var delpoint;
var endpoint;
var delcatid = '';
var artcounter = 0;
var artcounterArr = new Array();
$(".sortli").each(function (){
var atid = this.id.split('_');
//if(atid[2]!=cat_id)return;
if(this.id == del_aw){
deleted = 'yes';
delcatid = atid[2];
$(this).remove();
op = true;
i=i+1;
delpoint=i-1;
//alert('D'+delpoint);
//return;
}
if(atid[2]==cat_id){endpoint = i-1;artcounter=artcounter+1;}
else if(j==0 && artcounter > 0){
if(artcounter>0)artcounter = artcounter-1;
//else artcounterArr[j] = 0;
artcounterArr[j] = artcounter;
j=j+1;
artcounter = 0;
}
i = i + 1;
});
//alert(delpoint)
//alert(endpoint);
//alert(artcounterArr[0]);
if(op){
for(var k=delpoint; k<counter-1;k++){
var orderVal1 = tempOrderArr[k];
if(k<endpoint)document.getElementById('sortvalid_'+(k+1)).innerHTML = orderVal1;
document.getElementById('sortvalid_'+(k+1)).id = 'sortvalid_'+(k);
document.getElementById('sortdn_'+(k+1)).id = 'sortdn_'+(k);
document.getElementById('sortup_'+(k+1)).id = 'sortup_'+(k);
var t = tempIdArr[(k+1)].split('#');
t=t[0];
document.getElementById(tempIdArr[(k+1)]).id = t+'#'+k;
}
$(".rowHead").each(function (){
var taid = this.id;
var sp = this.id.split("^");
var a1 = sp[1];
//alert(a1);
//alert(cat_id);
if(parseInt(a1)>parseInt(cat_id)){
var a2 = sp[2];
var ta = 'lititle^'+a1+'^';
//alert(ta);
document.getElementById(taid).id = ta+(a2-1);
}
});
var a2temp;
var a1temp;
var delcat=null;
var rowHeadLast;
$(".rowHead").each(function (){
//var taid = this.id;
rowHeadLast = this;
var sp = this.id.split("^");
var a1 = sp[1];
var a2 = sp[2];
if(a2temp == a2 && delcat==null){delcat = a2temp; delcatid=a1temp;}
a2temp = a2;
a1temp = a1;
});
var delok = false;
$(".rowHead").each(function (){
//var taid = this.id;
//alert(deleted);
var sp = this.id.split("^");
var a1 = sp[1];
var a2 = sp[2];
if(delcat == a2 && a1==delcatid && deleted==''){delok= true;deleted='yes';$(this).remove();}
});
//alert(delcatid);
//if(!artcounterArr[0])alert('d');
if(!delok){
$(".rowHead").each(function (){
var sp = this.id.split("^");
var cid_t = sp[1];
if(!artcounterArr[0] && delcatid == cid_t)$(this).remove();
//else if(artcounterArr[0]<=0)$(this).remove();
});
}
if(deleted ==''){
$(rowHeadLast).remove();
}
}
setDivsInArray();
//$(".pleaseWait").dialog("close");
closeLightBox();
}
else if(status == 'DBDelete:error'){
//$('#row_'+artwork_id).fadeOut(3500);
$('#divStatus').fadeIn(500);
$('#divStatus').html('<b>Artwork Delete Error</b>');
$('#divStatus').fadeOut(4500);
}
}
});
}
it's quite long , I think I don't need all of those stuff if the requirement is just delete the data when "Yes" was clicked from the confirm pop up box
now here's the delete PHP function
function deleteArtWork($artwork_id,$category_id){
$artwork_cat_lookup_del = "delete from artwork_category_lookup where artwork_id = '$artwork_id' AND category_id='$category_id'";
if(mysql_query($artwork_cat_lookup_del)){
$userObj = new User();
$allArtWorkByCat = $userObj->allArtWorkByCat($category_id);
for($itr = 0; $itr<count($allArtWorkByCat); $itr++){
$ordr = $itr + 1;
$art_id = $allArtWorkByCat[$itr]['artwork_id'];
$updateSQL = "update artwork_category_lookup set artwork_display_order='$ordr' where artwork_id = '$art_id' AND category_id = '$category_id'";
mysql_query($updateSQL);
}
$action = $userObj->userActions('Artwork id: '.$artwork_id.' is deleted', 'Gallery');
$userObj->setActionintoDB($action);
echo 'done';
}
else echo 'DBDelete:error';
return;
I don't think that you want to start changing that code above as that is used to pass the relevant data to the php script via ajax.
What you need is a javascript prompt to intercept the link click and give the user an option to continue or cancel the deletion action. Is this correct?
http://www.tizag.com/javascriptT/javascriptconfirm.php
At the start of the "deleteThisArtWork" javascript function you need to display a prompt.
function deleteThisArtWork(artwork_id){
var answer = confirm("Are you sure you want to delete this record?");
if (answer){
//do the rest of the function as usual, i.e. delete row via ajax.
}else{
return false;
}
}
That should stop the user from accidentally deleting a record without at least having to accidentally click on a confirmation popup as well!
If you want to make the text in the confirm popup dynamic, you would need to either pass in the dynamic text as a variable to the "deleteThisArtwork" method or draw it from another element on the page using some javascript.