I'm using the 'Choose an Image' option of KCFinder (seen here) and would like to know how/if I can have multiple image areas rather than just one?
Here is my html/php code with 3 instances of the image/upload area (wrapped in a 'form' and saved to the database on submit):
<label>Logo: </label><div class="image" onclick="openKCFinder(this)"><img src="'.$_POST['logo'].'" alt="" id="img" /></div>
<input type="hidden" name="logo" value="'.$_POST['logo'].'" id="image" /> <br />
<label>Header Image: </label><div class="image" onclick="openKCFinder(this)"><img src="'.$_POST['h_image'].'" alt="" id="img" /></div>
<input type="hidden" name="h_image" value="'.$_POST['h_image'].'" id="image" /> <br />
<label>Side Advert Image: </label><div class="image" onclick="openKCFinder(this)"><img src="'.$_POST['side_advert'].'" alt="" id="img" /></div>
<input type="hidden" name="side_advert" value="'.$_POST['side_advert'].'" id="image" /> <br />
Here is my code for opening the image uploader:
function openKCFinder(div) {
window.KCFinder = {
callBack: function(url) {
window.KCFinder = null;
div.innerHTML = '<div style="margin:5px">Loading...</div>';
var img = new Image();
img.src = url;
img.onload = function() {
div.innerHTML = '<img id="img" src="' + url + '" />';
$('#image').attr('value', url);
var img = document.getElementById('img');
var o_w = img.offsetWidth;
var o_h = img.offsetHeight;
var f_w = div.offsetWidth;
var f_h = div.offsetHeight;
if ((o_w > f_w) || (o_h > f_h)) {
if ((f_w / f_h) > (o_w / o_h))
f_w = parseInt((o_w * f_h) / o_h);
else if ((f_w / f_h) < (o_w / o_h))
f_h = parseInt((o_h * f_w) / o_w);
img.style.width = f_w + "px";
img.style.height = f_h + "px";
} else {
f_w = o_w;
f_h = o_h;
}
img.style.marginLeft = parseInt((div.offsetWidth - f_w) / 2) + 'px';
img.style.marginTop = parseInt((div.offsetHeight - f_h) / 2) + 'px';
img.style.visibility = "visible";
}
}
};
window.open('http://www.websitename/admin/ckeditor/kcfinder/browse.php?type=images&dir=images/public',
'kcfinder_image', 'status=0, toolbar=0, location=0, menubar=0, ' +
'directories=0, resizable=1, scrollbars=0, width=800, height=600'
);
}
How would you get it so that the image uploader works independantly for each image area? At the moment it will only add an image to the first image area as they are all using the same id's.
Not sure if I've explained this correctly but here goes... many thanks in advance, s.
I guess this will do (using jquery traversing to find img element):
function openKCFinder(div) {
window.KCFinder = {
callBack: function(url) {
div.innerHTML = '<div style="margin:5px">Loading...</div>';
var img = new Image();
img.src = url;
img.onload = function() {
var img = $(div).html('<img class="img" src="' + url + '" />').children('img').attr('value', url).get(0); // using jquery you can get the desirent img element:)
var o_w = img.offsetWidth;
var o_h = img.offsetHeight;
var f_w = div.offsetWidth;
var f_h = div.offsetHeight;
if ((o_w > f_w) || (o_h > f_h)) {
if ((f_w / f_h) > (o_w / o_h))
f_w = parseInt((o_w * f_h) / o_h);
else if ((f_w / f_h) < (o_w / o_h))
f_h = parseInt((o_h * f_w) / o_w);
img.style.width = f_w + "px";
img.style.height = f_h + "px";
} else {
f_w = o_w;
f_h = o_h;
}
img.style.marginLeft = parseInt((div.offsetWidth - f_w) / 2) + 'px';
img.style.marginTop = parseInt((div.offsetHeight - f_h) / 2) + 'px';
img.style.visibility = "visible";
}
}
};
window.open('http://www.websitename/admin/ckeditor/kcfinder/browse.php?type=images&dir=images/public',
'kcfinder_image', 'status=0, toolbar=0, location=0, menubar=0, ' +
'directories=0, resizable=1, scrollbars=0, width=800, height=600'
);
}
Related
i am poorly trapped and also not getting any proper support from the Godaddy customer care. I have a comment section which is working perfectly on localhost and some other hosting but it is not working on Godaddy hosting. I don't understand, why this only occurs on godaddy.
Here is my html :
<div class="comment-form-container">
<form id="frm-comment">
<div class="input-row">
<input type="hidden" name="comment_id" id="commentId" placeholder="Name" /> <input class="input-field" type="text" name="name" id="name" placeholder="Name" />
</div>
<div class="input-row">
<textarea class="input-field" type="text" name="comment" id="comment" placeholder="Add a Comment"> </textarea>
</div>
<div>
<input type="button" class="btn-submit" id="submitButton" value="Publish" /><div id="comment-message">Comments Added Successfully!</div>
</div>
</form>
</div>
<div id="output"></div>
Here is my script :
function postReply(commentId) {
$('#commentId').val(commentId);
$("#name").focus();
}
$("#submitButton").click(function () {
$("#comment-message").css('display', 'none');
var str = $("#frm-comment").serialize();
$.ajax({
url: "comment-add.php",
data: str,
type: 'post',
success: function (response) {
//var result = eval('(' + response + ')');
//var result = eval('(' + JSON.stringify(response) + ')');
if (response) {
$("#comment-message").css('display', 'inline-block');
$("#name").val("");
$("#comment").val("");
$("#commentId").val("");
listComment();
} else {
alert("Failed to add comments !");
return false;
}
}
});
});
$(document).ready(function () {
listComment();
});
function listComment() {
$.post("comment-list.php",
function (data) {
var data = JSON.parse(data);
var comments = "";
var replies = "";
var item = "";
var parent = -1;
var results = new Array();
var list = $("<ul class='outer-comment'>");
var item = $("<li>").html(comments);
for (var i = 0; (i < data.length); i++)
{
var commentId = data[i]['comment_id'];
parent = data[i]['parent_comment_id'];
if (parent == "0")
{
comments = "<div class='comment-row'>"+
"<div class='comment-info'><span class='commet-row-label'>from</span> <span class='posted-by'>" + data[i]['comment_sender_name'] + " </span> <span class='commet-row-label'>at</span> <span class='posted-at'>" + data[i]['date'] + "</span></div>" +
"<div class='comment-text'>" + data[i]['comment'] + "</div>"+
"<div><a class='btn-reply' onClick='postReply(" + commentId + ")'>Reply</a></div>"+
"</div>";
var item = $("<li>").html(comments);
list.append(item);
var reply_list = $('<ul>');
item.append(reply_list);
listReplies(commentId, data, reply_list);
}
}
$("#output").html(list);
});
}
function listReplies(commentId, data, list) {
for (var i = 0; (i < data.length); i++)
{
if (commentId == data[i].parent_comment_id)
{
var comments = "<div class='comment-row'>"+
" <div class='comment-info'><span class='commet-row-label'>from</span> <span class='posted-by'>" + data[i]['comment_sender_name'] + " </span> <span class='commet-row-label'>at</span> <span class='posted-at'>" + data[i]['date'] + "</span></div>" +
"<div class='comment-text'>" + data[i]['comment'] + "</div>"+
"<div><a class='btn-reply' onClick='postReply(" + data[i]['comment_id'] + ")'>Reply</a></div>"+
"</div>";
var item = $("<li>").html(comments);
var reply_list = $('<ul>');
list.append(item);
item.append(reply_list);
listReplies(data[i].comment_id, data, reply_list);
}
}
}
And I am 100% sure that there is no connectivity problem with database. Please help me out.
here is comment-add.php
<?php
require_once ("db.php");
date_default_timezone_set('Asia/Kolkata');
$commentId = isset($_POST['comment_id']) ? $_POST['comment_id'] : "";
$comment = isset($_POST['comment']) ? $_POST['comment'] : "";
$commentSenderName = isset($_POST['name']) ? $_POST['name'] : "";
$date = date("Y-m-d H:i:s", time());
$sql = "INSERT INTO tbl_comment(parent_comment_id,comment,comment_sender_name,date) VALUES ('" . $commentId . "','" . $comment . "','" . $commentSenderName . "','" . $date . "')";
$result = mysqli_query($conn, $sql);
if (! $result) {
$result = mysqli_error($conn);
}
echo $result;
?>
here is comment-list.php
<?php
require_once ("db.php");
$sql = "SELECT * FROM tbl_comment ORDER BY parent_comment_id asc, comment_id asc";
$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($record_set, $row);
}
mysqli_free_result($result);
mysqli_close($conn);
echo json_encode($record_set);
?>
here is db.php
<?php
$conn = mysqli_connect("localhost","xxxxxxxxx","xxxxxxxx","xxxxxxxxxx");
?>
How to insert dynamically generated field values to backend using mysql.
Im trying to add rows with text box and drop down using jquery and auto saving
the field values at regular intervals.
So i need to fetch the ids of the textboxes and drop down, but currently i get the id of only the first text box and drop down.
$(function() {
$("#btnAdd").bind("click", function() {
AddControl();
});
$("#btnGet").bind("click", function() {
var values = "";
$("input[name=DynamicTextBox]").each(function() {
values += $(this).val() + "\n";
});
alert(values);
});
$("body").on("click", ".remove", function() {
$(this).closest("div").remove();
var i = 1;
var Ids = [];
$('[id*=ddl]').each(function() {
$(this).attr("id", "ddl" + i);
Ids.push(i);
i++;
});
$('[id*=hfDDLId]').val(parseInt($('[id*=hfDDLId]').val()) - 1);
var resultIds = Ids.join(',');
$('[id*=hfDropDownIds]').val(resultIds);
});
});
function AddControl() {
var Id = parseInt($('[id*=hfDDLId]').val()) + 1;
var ddlId = "ddl" + (Id);
var div = $("<div />");
div.html(getDropDownList(ddlId, ddlId));
div.append(GetDynamicTextBox(''));
$("#TextBoxContainer").append(div);
$('[id*=hfDDLId]').val(Id);
var previousDropDownId = $('[id*=hfDropDownIds]').val();
if (previousDropDownId != '') {
$('[id*=hfDropDownIds]').val(previousDropDownId + ',' + Id);
} else {
$('[id*=hfDropDownIds]').val(Id);
}
return false;
}
function getDropDownList(name, id) {
var combo = $("<select></select>").attr("id", id).attr("name", name).attr("runat", "server").attr("class", "class").attr("required", "required");
combo.append("<option value=" + "" + ">" + "Select Category" + "</option>");
combo.append("<option value=" + "1" + ">" + "1" + "</option>");
combo.append("<option value=" + "2" + ">" + "2" + "</option>");
combo.append("<option value=" + "3" + ">" + "3" + "</option>");
return combo;
}
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" id="ingr_name" type="text" value = "' + value + '" required/> ' + '<input name = "DynamicTextBox" type="text" value="' + value + '" required/> ' + '<input type="button" value="Remove" class="remove" />'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" runat="server">
<div>
<input id="btnAdd" type="button" value="Add" />
<br/>
<br/>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br/>
<input type="hidden" id="hfSelectedValue" runat="server" />
<input type="hidden" id="hfDropDownIds" value="" runat="server" />
<input id="btnGet" type="button" value="Get Values" />
<input type="hidden" id="hfDDLId" value="0" />
</div>
</form>
Code for inserting in the backend
Assunimg i have given the id for the text box as 'ingr_name' im posting the same as :
<?php
$con=mysqli_connect("localhost","root","pass","DB");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['txt_area']) && $_POST['txt_area'] != '') {
$ingr_name = mysqli_real_escape_string($con,$_POST['ingr_name']);
$qry = "Select count(*) as cnt from table";
$res = mysqli_query($con,$qry);
$row = mysqli_fetch_array($res);
if ($row['cnt'] == 0) {
$qry_ins = 'my insert query';
}
?>
#SachinSachin if you want to insert only one text box value try the below code
function insert_data(){
var url = "insert.php";
$.ajax({
url : url,
type: "POST",
data: $('#formid').serialize(),
success: function(data)
{
alert(data);
}
});
}
call this function on submit button and in insert.php you get the values using post method as usual and insert them in mysql. if it is success print echo "inserted"; else print echo "failed"; you will get this status in alert message in above insert_data() function. Here i assumed you are using php as backend if not use your language with same process.
All else is working fine
jQuery:
$(".edit").click(function()
{
var user_id=$(this).attr('id');
var options = '';
$.getJSON("do_find_courses.php",{user_id:user_id}, function(data){
for (var i = 0; i < data.length; i++) {
if(data[i].optionDisplay=="No File Categories")
{
options = '<option disabled="disabled" selected="selected">No products</option>';
}
else
{
options +=' <input name="' + data[i].optionValue + '" type="checkbox" value="' + data[i].optionDisplay + '" />'+ data[i].optionDisplay +'<br>';
//options += '<option value="' + data[i].optionValue + '">' + data[i].optionDisplay + '</option>';
}
}
$("#chkbox"+user_id).slideToggle( "slow" ).html(options);
//$("#chkbox"+user_id).html(options);
});
return false;
});
php code generated for the a href
<?php
$get_students=mysql_query("SELECT user_id ,surname,name, admin FROM users WHERE users.admin=0 ORDER BY users.surname ASC") or die(mysql_error());
while($row=mysql_fetch_array($get_students))
{
echo'
<tr>
<td><h3>'.$row['surname'].'</h3></td>
<td>'.$row['name'].'</td>
<td><div id="chkbox'.$row['user_id'].'"></div></td>
<td>Delete
Edit</td>
</tr>';}
?>
$(document).ready(function{
$(".edit").unbind('click');
$(".edit").click(function(){ bla bla bla});
});
I have a page where the user can add dynamically created textareas that are nested in divs.
I am trying to insert the added textareas
the problem i have is if I add 3 textareas and then remove the second one and then submit the amount of submitted textareas is 2 but the id of the two areas are 1 and 3 and when i try to add with a for loop the 2nd textarea has no value
how else can I insert into the db the posted text areas except with a for loop.
heres the code
php insert code:
<?
$page_ref="170";
$template_ref="15";
if($_SERVER['REQUEST_METHOD'] == "POST")
{
mysql_query("DELETE FROM site_content WHERE page_ref='$page_ref' AND template_ref='$template_ref' AND box_type='text'");
$q=count($_POST["textarea"])+1;
for($m=1; $m<$q;$m++)
{
$left=$_POST["left"][$m];
$top=$_POST["top"][$m];
$height=$_POST["height"][$m];
$width=$_POST["width"][$m];
$text=addslashes($_POST["textarea"][$m]);
$j=$m+1;
$drag_id++;
$box_type=$_POST['box_type'][$m];
$box_id=$_POST['id'][$m];
mysql_query("INSERT INTO site_content(page_ref, template_ref, content, box_id, box_type, box_top, box_left, box_width, box_height)VALUES('$page_ref','$template_ref','$text','$box_id','$box_type','$top','$left','$width','$height')");
}
}
?>
javascript:
function NewTextArea(id) {
id = id + i;
var newdiv = document.createElement('div');
newdiv.setAttribute('id', id);
newdiv.setAttribute('class', 'dragbox');
newdiv.setAttribute('iterate', i);
newdiv.style.position = "relative";
newdiv.style.top = p;
newdiv.style.left = p;
newdiv.style.cursor = 'move';
newdiv.innerHTML = "</div><br><textarea id='" + i + "' onDblClick='editor1(" + i + ")' name='textarea[" + i + "]' class='textarea1' style='position:absolute; top:10px;left:0px;overflow-y: auto;background-color:transparent;border: 1px solid #00FFFF; '>text here" + i + "</textarea>";
newdiv.innerHTML = newdiv.innerHTML + "<br><input type='hidden' value='" + i + "' name='id[" + i + "]'><br><input name='box_type[" + i + "]' type='hidden' value='text'/>";
newdiv.innerHTML = newdiv.innerHTML + "<br><input type='hidden' value='300' name='width[" + i + "]' id='width" + i + "'><br><input type='hidden' value='75' name='height[" + i + "]' id='height" + i + "'>";
newdiv.innerHTML = newdiv.innerHTML + "<br><input type='hidden' value='0' name='left[" + i + "]' id='left" + i + "'><br><input type='hidden' value='0' name='top[" + i + "]' id='top" + i + "'>";
document.getElementById("frmMain").appendChild(newdiv);
var but = document.createElement('input');
but.setAttribute('type', 'button');
but.setAttribute('class', 'removebutton');
but.style.visibility = "visible";
but.style.float = "right";
but.style.position = "absolute";
but.style.left = "300px";
but.style.top = "0px"
but.onclick = function () {
if (confirm('Really delete?')) {
document.getElementById("frmMain").removeChild(newdiv);
document.getElementById(id).removeChild(but);
document.getElementById(id).removeChild(newbr);
}
}
newbr = document.createElement('BR');
document.getElementById(id).appendChild(newbr);
document.getElementById(id).appendChild(but);
$(function() {
$("#" + i).resizable({
autoHide: true
})
$("#" + id).hover(function() {
$("#" + i).css('border', '1px solid #00FFFF');
});
$("#" + id).mouseleave(function() {
$("#" + i).css('border', '0px');
});
$("#" + i).resizable({
stop: function (event, ui) {
var width = ui.size.width;
var height = ui.size.height;
$("#" + id).find(".removebutton").css('left', +width + 'px');
// alert("width="+width+"height="+height);
ValProportions(width, height, ui.element.context.id);
}
});
$("#" + id).draggable({
stop: function(event, ui) {
Stoppos = $(this).position();
$("div#stop").text("STOP: \nLeft: " + Stoppos.left + "\nTop: " + Stoppos.top);
// alert("left="+Stoppos.left+"top="+Stoppos.top);
ValPostion(Stoppos.left, Stoppos.top, $(this).attr('iterate'));
}
});
$("#" + i).draggable({
handle: "#handle"
});
});
function ValProportions(defaultwidth, defaultheight, id) {
$('#width' + id).val(defaultwidth);
$('#height' + id).val(defaultheight);
}
function ValPostion(defaultleft, defaulttop, id) {
$('#left' + id).val(defaultleft);
$('#top' + id).val(defaulttop);
}
p = p + 25;
i++;
$('.dragbox').click(function() {
$(".removebutton").css('visibility', 'hidden');
$("#" + i).css('border', '0px');
$(this).css('border', '1px solid #000');
$(this).css('background-color', 'red');
$(this).css('background-image', 'url(img/move.png)');
$(this).css('background-repeat', 'no-repeat');
$(this).css('width', '15px');
$(this).css('height', '15px');
$(this).find(".removebutton").css('visibility', 'visible');
$(this).find("#" + i).css('border', '1px solid #00FFFF');
});
$('.dragbox').focusout(function(e) {
$("#" + i).css('border', '0px');
$('.dragbox').css('background-color', 'transparent');
$('.dragbox').css('width', '0px');
$('.dragbox').css('border', '0px');
$(this).css('border', '0px');
$(this).css('background-color', 'transparent');
$(this).css('width', '0px');
});
}
html code:
<form id="frmMain" name="frmMain" enctype="multipart/form-data" action="dynamic_div5.php" method="post">
<input id="btn1" type="button" value="Add New textbox" onClick="NewTextArea('draggable');"/>
<input type="submit" value="Save Page" >
<div id="content">
<?
$sql=mysql_query("SELECT * FROM site_content WHERE page_ref='$page_ref' AND template_ref='$template_ref' ORDER BY box_id DESC");
$numrows=mysql_num_rows($sql);
while($row=mysql_fetch_array($sql))
{
?>
<script>OldTextArea('<? echo $row['box_id']; ?>','draggable','<? echo $row['box_top']; ?>','<? echo $row['box_left']; ?>','<? echo $row['box_width']; ?>','<? echo $row['box_height']; ?>','<? echo $row["content"]; ?>');</script>
<?
}
?>
</div>
</form>
The Easyway is create textareas as array
<textarea name="textarea[]"></textarea>
<textarea name="textarea[]"></textarea>
<textarea name="textarea[]"></textarea>
and in loop
<?php
foreach($_POST['textarea'] as $i => $value)
{
//Save Here
}
?>
and you will avoid missing textareas
Use this method:
<textarea name="somename[]"></textarea>
<textarea name="somename[]"></textarea>
<textarea name="somename[]"></textarea>
<textarea name="somename[]"></textarea>
and than in PHP you will have array:
$somename[0]; $somename[1]; $somename[2]; $somename[3]; ...
so, you must to change in your code (js)
newdiv.innerHTML = "</div><br><textarea id='"+i +"' onDblClick='editor1("+i+")' name='textarea[]' class='textarea1' style='position:absolute; top:10px;left:0px;overflow-y: auto;background-color:transparent;border: 1px solid #00FFFF; '>text here"+i+"</textarea>";
and (in PHP)
$q=count($_POST["textarea"]);
for($m=0; $m<$q;$m++)
I want to insert values from another form field in one text area. There are multiple fields, each placed in different forms with different submit buttons. Whenever the button is clicked, the values in that form should be inserted into the text area.
The fields are generated in an array. I have assigned the same id name for every field. This is to make every field's values belong to that textarea. My problem is, only the first field insert its value into the textarea when I click its button.Other fields not working. How could I fix this?
Here is the code:
<script type="text/javascript">
window.onload = function() {
btn1 = document.getElementById("btnInsertText1");
myText1 = document.getElementById("myTextArea1");
text1 = document.getElementById("textToInsert1");
btn1.onclick = function(){
insertAtCursor(myText1, text1.value);
}
}
function insertAtCursor(myField, myValue) {
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
}
else {
myField.value += myValue;
}
}
</script>
<textarea id="myTextArea1" name="update" cols="85" rows="22">
Testing. Values from another field will be inserted here.
</textarea>
<?php
$ref = "
SELECT *
FROM reftext1_objective
WHERE projectid='$id'";
$refresult = mysql_query($ref);
while($row = mysql_fetch_array($refresult))
{?>
<form>
<input id="textToInsert1" type="text" value="<?php echo $row[$text];?>" readonly="true">
<input type="button" id="btnInsertText1" value="<<" />
</form><br><?php
}
As stated in my comment on the question, the problem is due to the duplicated element ids in the loop in your PHP code. To fix it, try this:
<script type="text/javascript">
$(function() {
var textarea = document.getElementById("myTextArea1");
$(".button").click(function() {
var $parentForm = $(this).closest("form");
var text = $(".insert-text", $parentForm).val();
insertAtCursor(textarea, text);
});
});
function insertAtCursor(myField, myValue) {
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
}
else {
myField.value += myValue;
}
}
</script>
<textarea id="myTextArea1" name="update" cols="85" rows="22">
Testing. Values from another field will be inserted here.
</textarea>
<?php
$ref = "SELECT * FROM reftext1_objective WHERE projectid = '$id'";
$refresult = mysql_query($ref);
while ($row = mysql_fetch_array($refresult))
{ ?>
<form>
<input class="insert-text" type="text" value="<?php echo $row[$text];?>" readonly="true">
<input type="button" class="button" value="<<" />
</form><br>
<?php }
?>
Example fiddle