How to get total value on dynamic value? - php

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>

Related

XML parse in AJAX

<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!

# 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();
});
});

How to to output json into a div

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);
})
})();

How to dynamically create an instance of tinymce using javascript?

How to dynamically create an instance of tinymce using javascript? This is my code so far:
javascript:
$(function()
{
$("#onesnippet").click(function()
{
alert("One Snippet");
var idiv = document.getElementById('translations');
var newdiv = document.createElement('div');
newdiv.id = 10;
idiv.appendChild(newdiv);
var latestdiv = document.createElement('div')
latestdiv.id = 4;
newdiv.appendChild(latestdiv);
var textarea1 = document.createElement('textarea');
textarea1.id = "mceEditor3";
textarea1.className = "mceEditor";
latestdiv.appendChild(textarea1);
});
});
php file to include tinymce :
<script>
tinymce.init({mode : "specific_textareas", element : "mceEditor,mceEditor1,mceEditor2,mceEditor3", editor_selector : "mceEditor"});
</script>
You finish your code, and then add editor initiate code.
$(function()
{
$("#onesnippet").click(function()
{
alert("One Snippet");
var idiv = document.getElementById('translations');
var newdiv = document.createElement('div');
newdiv.id = 10;
idiv.appendChild(newdiv);
var latestdiv = document.createElement('div')
latestdiv.id = 4;
newdiv.appendChild(latestdiv);
var textarea1 = document.createElement('textarea');
textarea1.id = "mceEditor3";
textarea1.className = "mceEditor";
latestdiv.appendChild(textarea1);
tinymce.init({mode : "specific_textareas", element : "mceEditor,mceEditor1,mceEditor2,mceEditor3", editor_selector : "mceEditor"});
});
});

Passing DOM table variables to PHP

I am not very experienced just a learner.
Now come to the question.
I have a dynamic table codes are below: works fine as intended.
<head>
<style type="text/css">
<!--
#tblitemsgrid
td {
padding: 0.5em;
}
.classy0 { background-color: #234567; color: #89abcd; }
.classy1 { background-color: #89abcd; color: #234567; }
th {
padding: 0.5em;
background:#39C;
text-align:center;
}
-->
</style>
<script type="text/javascript">
var INPUT_NAME_PREFIX = 'input'; // this is being set via script
var RADIO_NAME = 'totallyrad'; // this is being set via script
var TABLE_NAME = 'tblitemsgrid'; // this should be named in the HTML
var ROW_BASE = 1; // first number (for display)
var hasLoaded = false;
window.onload=fillInRows;
function fillInRows()
{
hasLoaded = true;
addRowToTable();
}
// CONFIG:
// myRowObject is an object for storing information about the table rows
function myRowObject(one, two, three, four, five)
{
this.one = one; // text object
this.two = two; // text object
this.three = three; // text object
this.four = four; // text object
}
/*
* insertRowToTable
* Insert and reorder
*/
function insertRowToTable()
{
if (hasLoaded) {
var tbl = document.getElementById(TABLE_NAME);
var rowToInsertAt = tbl.tBodies[0].rows.length;
for (var i=0; i<tbl.tBodies[0].rows.length; i++) {
}
addRowToTable(rowToInsertAt);
reorderRows(tbl, rowToInsertAt);
}
}
/*
* addRowToTable
function addRowToTable(num)
{
if (hasLoaded) {
var tbl = document.getElementById(TABLE_NAME);
var nextRow = tbl.tBodies[0].rows.length;
var iteration = nextRow + ROW_BASE;
if (num == null) {
num = nextRow;
} else {
iteration = num + ROW_BASE;
}
// add the row
var row = tbl.tBodies[0].insertRow(num);
// CONFIG: requires classes named classy0 and classy1
row.className = 'classy' + (iteration % 2);
// CONFIG: This whole section can be configured
// cell 0 - text - Serial Number
var cell0 = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cell0.appendChild(textNode);
// cell 1 - input text - Account name
var cell1 = row.insertCell(1);
var txtInpACC = document.createElement('input');
txtInpACC.setAttribute('type', 'text');
txtInpACC.setAttribute('name', 'accname' + iteration);
txtInpACC.setAttribute('size', '40');
txtInpACC.setAttribute('value', iteration);
cell1.appendChild(txtInpACC);
// cell 2 - input box- Dr amount
var cell2 = row.insertCell(2);
var txtInpDR = document.createElement('input');
txtInpDR.setAttribute('type', 'text');
txtInpDR.setAttribute('name', 'DrAmount' + iteration);
txtInpDR.setAttribute('size', '10');
txtInpDR.setAttribute('value', iteration); // iteration included for debug purposes
cell2.appendChild(txtInpDR);
// cell 3 - input box- Cr amount
var cell3 = row.insertCell(3);
var txtInpCR = document.createElement('input');
txtInpCR.setAttribute('type', 'text');
txtInpCR.setAttribute('name', 'CrAmount' + iteration);
txtInpCR.setAttribute('size', '10');
txtInpCR.setAttribute('value', iteration); // iteration included for debug purposes
cell3.appendChild(txtInpCR);
// cell 4 - input button - Delete
var cell4 = row.insertCell(4);
var btnEl = document.createElement('input');
btnEl.setAttribute('type', 'button');
btnEl.setAttribute('value', 'Delete');
btnEl.onclick = function () {deleteCurrentRow(this)};
cell4.appendChild(btnEl);
// Pass in the elements you want to reference later
// Store the myRow object in each row
row.myRow = new myRowObject(textNode, txtInpACC, txtInpDR, txtInpCR, btnEl);
}
}
// CONFIG: this entire function is affected by myRowObject settings
function deleteCurrentRow(obj)
{
if (hasLoaded) {
var oRows = document.getElementById('tblitemsgrid').getElementsByTagName('tr');
var iRowCount = (oRows.length - 2);
if (iRowCount <1+1) {
alert('Your table has ' + iRowCount + ' row(s). Row count can not be zero.');
return
}
var delRow = obj.parentNode.parentNode;
var tbl = delRow.parentNode.parentNode;
var rIndex = delRow.sectionRowIndex;
var rowArray = new Array(delRow);
deleteRows(rowArray);
reorderRows(tbl, rIndex);}
}
function reorderRows(tbl, startingIndex)
{
if (hasLoaded) {
if (tbl.tBodies[0].rows[startingIndex]) {
var count = startingIndex + ROW_BASE;
for (var i=startingIndex; i<tbl.tBodies[0].rows.length; i++) {
// CONFIG: next line is affected by myRowObject settings
tbl.tBodies[0].rows[i].myRow.one.data = count; // text
// CONFIG: next line is affected by myRowObject settings
tbl.tBodies[0].rows[i].myRow.two.name = INPUT_NAME_PREFIX + count; // input text
var tempVal = tbl.tBodies[0].rows[i].myRow.two.value.split(' ');
tbl.tBodies[0].rows[i].myRow.two.value = count + ' was' + tempVal[0];
// CONFIG: next line is affected by myRowObject settings
tbl.tBodies[0].rows[i].myRow.four.value = count; // input radio
// CONFIG: requires class named classy0 and classy1
tbl.tBodies[0].rows[i].className = 'classy' + (count % 2);
count++;
}
}
}
}
function deleteRows(rowObjArray)
{
if (hasLoaded) {
for (var i=0; i<rowObjArray.length; i++) {
var rIndex = rowObjArray[i].sectionRowIndex;
rowObjArray[i].parentNode.deleteRow(rIndex);
}
}
}
function openInNewWindow(frm)
{
// open a blank window
var aWindow = window.open('', 'TableAddRow2NewWindow',
'scrollbars=yes,menubar=yes,resizable=yes,toolbar=no,width=400,height=400');
// set the target to the blank window
frm.target = 'TableAddRow2NewWindow';
// submit
frm.submit();
}
</script>
</head>
<body>
<form action="tableaddrow_nw.php" method="get">
<p>
<input type="button" value="Add" onclick="addRowToTable();" />
<input type="button" value="Insert [I]" onclick="insertRowToTable();" />
<!--<input type="button" value="Delete [D]" onclick="deleteChecked();" />-->
<input type="button" value="Submit" onclick="openInNewWindow(this.form);" />
</p>
<table border="0" cellspacing="0" id="tblitemsgrid" width=600>
<thead>
<tr>
<th colspan="5">Sample table</th>
</tr>
<tr>
<th>E.#</th>
<th>Account name</th>
<th>Debit</th>
<th>Credit</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
</form>
</body>
</html>
This is a processing page:
<head>
<title>Table Add Row - new window</title>
<script language="JavaScript">
<!--
function printToPage()
{
var pos;
var searchStr = window.location.search;
var searchArray = searchStr.substring(1,searchStr.length).split('&');
var htmlOutput = '';
for (var i=0; i<searchArray.length; i++) {
htmlOutput += searchArray[i] + '<br />';
}
return(htmlOutput);
}
//-->
</script>
</head>
<body>
<b>MREDKJ's Table Add Row</b>
<br />
Below should be the name/value pairs that were submitted:
<p>
<script language="JavaScript">
<!--
document.write(printToPage());
//-->
</script>
</p>
</body>
</html>
the above displays a result:
accname1=1
DrAmount1=1
CrAmount1=1
input2=2+was2
DrAmount2=2
CrAmount2=2
input3=3+was3
DrAmount3=3
CrAmount3=3
input4=4+was4
DrAmount4=4
CrAmount4=4
how can I pass javascript variables into PHP (which is server side and client side) in the above case ?
thanks alot in advance.
The way to pass variables from client-side to server-side is via HTTP Request. So either you redirect to a PHP page passing in the variable as GET query strings or POST data or you can also do an AJAX call of either GET or POST.
You can use jQuery and ajax to pass these informations to server easy way
And remember. PHP isn't client side language
$.ajax({
'url': 'ajax.php',
'type': 'POST',
'data': 'accname1='+accname1+'&input1='+input1+'&input2='+input2+'&input3='+input3+'&DrAmount1='+DrAmount1+'&DrAmount2='+DrAmount2+'&DrAmount3='+DrAmount3+'&CrAmount1='+CrAmount1'&CrAmount2='+CrAmount2'&CrAmount3='+CrAmount3,
'success': function(){
alert('data sent');
}
});

Categories