I've got 2 <div>'s, both contentEditable with values from a database.
It works displaying them and changing them BUT only the second time.
e.g. :
Clicking on the #stuff div
alerts me the value from the DB ( something like "Weather's ok" )
I change it to "New Value"
Clicking outside the div
Function alerting me the value from #stuff div ( still "Weather's okay" )
Clicking again inside the div and it now alerts me "New Value"
This leads to having to go into the div twice for it to accept the changes..
I tried it manualy to open save.php with the parameters and it saved directly!
I'm pretty sure this is something basic what I'm missing but I cant figure it out yet..
HTML :
<div id="test-container" style="border: 1px solid green;">
<div id="editable" contentEditable="true">
<?php echo $rst["content"]; ?>
</div>
<div id="stuff" contentEditable="true">
<?php echo $rst["stuff"]; ?>
</div>
<button id="save">Save Changes</button>
</div>
JS Function(s) :
var content = "";
var from = "";
/*
The code below shows the save button if anywhere in the editable div is clicked,
and hide the button if anywhere outside the div is clicked.
*/
$("#editable, #stuff").click(function (e) {
content = $(this).html();
from = (this.id);
alert(content);
$("#save").show();
e.stopPropagation();
});
$(document).click(function() {
alert(content);
$("#save").hide();
});
/*
The code below gets the data from the content variable and posts to the send.php file.
If the data is posted successfuly, the PHP file recieves the data and inserts to database, where the field is based on the form variable.
*/
$("#save").click(function (e) {
$.ajax({
url: 'save.php',
data: {
content: content,
from : from
}
});
});
The problem I found in your code is:
after the keyboard input DOM is updated not variable.
Try this:-
var content = "";
var from = "";
$("#editable, #stuff").click(function (e) {
content = $(this).html();
from = $(this.id);
console.log(content);
e.stopPropagation();
});
$(document).click(function() {
console.log(content);
});
$("#editable, #stuff").keyup(function(){
content = $(this).html();
from = $(this.id);
});
click here for the working fiddle
Related
I got a button which i want to reload on click. But only the button should be reloaded, not the rest of the page.
The button looks like this:
<a href="{$module_data.GM_PRODUCTS_BUTTON_BUY_NOW_URL}" id="click{php}echo ''.$counter.'';{/php}" class="addcart button_green button_set action_add_to_cart"{if $module_data.PRODUCTS_NAME != ''} title="{$module_data.PRODUCTS_NAME|replace:'"':'"'} {$txt.text_buy}"{/if}
onclick="return checkAddToCart(event, '{$module_data.QTY_DATA.ID}', {$product_stock}, {$product_max_order}, {$module_data.PRODUCTS_ID}, {php}echo $row['customers_basket_quantity']{/php}, {php}echo "'click".$counter."'";{/php});">
<span class="button-outer">
<span class="button-inner">{$button.add_to_cart}</span>
</span>
</a>
Now i told javascript that echo "'click".$counter."'"; is the clickid.
I tried the following thing to reload my page on click:
function checkAddToCart(event, tid, stock, maxallowed, pid, pquantity, clickid)
{
var clickid_string = clickid.toString();
var bought = Number($("#"+tid).val());
stock = Number(stock);
maxallowed = Number(maxallowed);
var ans = (bought>stock) || (bought > maxallowed);
if(ans)
{
event.stopPropagation();
event.preventDefault();
alert("Maximale Bestellmenge: " + Math.min(maxallowed, stock));
}
else {
$("#"+clickid_string).load("#"+clickid_string);
}
return !ans;
}
It is not working, and i have absolutly no idea why. By the ay, my system works with SMARTY tpl.
If you want to run a php script on click of a button you need to learn ajax. Ajax its just a simple way to use javascript, to run pages in background without reload the current page.
<span class="button-outer" onClick="addDataToDB(this);">...</span>
<script>
function addDataToDB(el) {
var elem = $(el);
/* GET ALL YOUR DATA*/
var name = ...
/* Create an AJAX request to your phpfunction */
}
</script>
Check some tutorials in youtube.
I would like to prepopulate the fields of a form I display in a modal view via jquery after getting the form HTML with an ajax query. I am prepopulating the fields via a document.getElementById call to set the value in a javascript function, with the values in the javascript function generated with php code.
The problem is that the fields I want to populate with values don't seem to exist even after the callback function from the AJAX call has imported the form code. When I check if the elements exist in my function to set the values of those elements, I see a null return, so the elements are not there. What's going on?
I can see that in the html source code, the php has put the correct form values in. However, I do not see the textarea value/innerHTML displayed. Rather the textarea is blank. Is there something tricky about text areas?
Thank you for any suggestions.
Here is the Jquery/javascript:
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<script>
$(function() {
var dialog, form,
dialog = $( "#dialog-form2" ).dialog({
autoOpen: false,
height: 550,
width: 400,
modal: true,
});
$( "#create-user2" ).button().on( "click", function() {
showform();
dialog.dialog( "open" );
});
});
</script>
<div id="dialog-form2" style="background-color: white; border: 4px solid #f1f1f1; padding: 20px;" >
</div>
<div id="dialog-form2" style="background-color: white; border: 4px solid #f1f1f1; padding: 20px;" ></div>
<script>
function showform()
{
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("dialog-form2").innerHTML=xmlhttp.responseText;
updateform();
}
}
xmlhttp.open("GET", "newinstructions.html");
xmlhttp.send();
}
function updateform()
{
document.getElementById('f1').value = '<?php echo $included;?>';
document.getElementById('f2').value = '<?php echo $id_bus;?>';
document.getElementById('f3').value = '<?php echo $deals_id;?>';
document.getElementById('f4').value = '<?php echo $_SESSION['token'];?>';
document.getElementById('details').innerHTML = '<?php echo $instructions1;?>';
document.getElementById('details').value = '<?php echo $instructions1;?>';
}
</script>
Here is the form:
<form method = "post" action = "changeinstructions.php">
<textarea rows = "8" cols = "60" name = "details" id = "details" ></textarea>
<input type = "hidden" name = "included" '/>
<input type = "hidden" name = "id" />
<input type = "hidden" name = "deals_id"/>
<input type = "hidden" name = "token" />
<br>
<input type="submit" tabindex="-1" >
</form>
And finally I include this in a php file as include_once('jquery.php') and I have verified that all the php variables exist and have values just before this include statement. Here is what the html source code looks like as resulting for the javscript function setting values:
function updateform()
{
document.getElementById('f1').value = '1';
document.getElementById('f2').value = '59';
document.getElementById('f3').value = '226';
document.getElementById('f4').value = '7a7dd52df381577c7b8e2518aa9b2808';
document.getElementById('details').innerHTML = ' dumb instructions';
document.getElementById('details').value = ' dumb instructions';
}
So the function updateform() has the right values, and this function should only be called after the form itself has been created. Yet no values appear on the form, and no values appear in the POST array after I submit the form. What gives? Thanks for any advice.
you want to populate the inserted values into a new popup modal or dialog ??
please explain more what you are trying do,
if iam correct , you dont need to re-include jquery code you can do this in a callback function instead
////edit
you can use .val() to set or get textarea
//edit
you are using a get in your ajax , while your form is using POST
i wounder if you are using $_GET or $_POST in your php , this is confusing
//
the solution as follows :
//
you need to select the textarea not by its id alone,
you need to select the top parent first ,
then second top parent
example :
if you open you console you will find it something like this (after the popup appear)
<div id="popup top div"><div id="another parent"><form><textarea id="details"> ,
all you need to do is something like
var target_textarea =$("#topid #secoundtopid #details") then use the target_textarea.val();
Basically, your ajax needs attention.
When the AJAX routine is run (and I recommend using jQuery, as it's simpler and much less typing -- see posts at bottom) the server sends the response back in the variable responseText. You cannot use <?php echo etc etc; ?> to get the returned data -- it isn't there. It's in the responseText variable.
Also, that variable is local to (and only available in) the xmlhttp.onreadystatechange function.
Simple AJAX:
AJAX request callback using jQuery
After you render the new page, the javascript needs to call the function updateform() to populate the html DOM.
window.onload=updateform;
You can also call it in the <body> element <body onload="updateform()">
I have a gallery with some images, and I have a link in each image to delete it:
<div class="galery">
echo '<ul>';
while ($result = $read->fetch(PDO::FETCH_ASSOC)){
echo '<li id="'.$result['id'].'">';
echo '<img src="'.$result['img'].'" />';
echo 'Delete';
echo '</li>';
}
echo '</ul>';
</div>
And then I have a jQuery script to delete my image using ajax:
I get my id of each image an then I have my ajax $.post:
var url = 'deleteImages.php';
$('.galery ul').on('click','.galerydel',function(){
var delid = $(this).attr('id');
$.post(url,{action:'del_images',image:delid},function(){
});
return false;
});
And then I have my php.file, where I get my image id $imageId = $_POST['image']; and action $_POST['action'];
and then I do my delete in my gallery table where id is = $imageId.
And this is working fine, but now I want to have a dialog message asking user if he have sure that wants to remove image,
so I have a div for a dialog like this:
<div class="delete_dialog">
<div class="delete">
<p>Do you really want to delete this image?</p>
Yes
No
</div>
</div>
And then I want to show this div when I click in my link to delete each image:
var url = 'deleteImages.php';
$('.galery ul').on('click','.galerydel',function(){
var delid = $(this).attr('id');
$('.delete_dialog').fadeIn("slow",function(){
('.delete').fadeIn("slow");
});
$.post(url,{action:'del_images',image:delid},function(){
});
return false;
}); ยด
And now, when I click in my delete link Im open my dialog, but Im also removing my news without answer to my dialog.
Do you know how can I use my dialog, if I click in yes I do my delete, but If I click in no I just close my dialog?
Im reading about this for hours, and I just saw examples using jQuery dialog, and its easy because we can use buttons (yes and no).
And I also saw examples with if(confirm(Do you really want to delete this image?){my ajax here} and it is also easy to do.
But Im trying to do with my own dialog, and like this I really dont know how we can do this.
Can you please give me some help??
What Im trying:
var url = 'deleteImages.php';
$('.galery ul').on('click','.galerydel',function(){
var delid = $(this).attr('id');
$('.delete_dialog').fadeIn("slow",function(){
('.delete').fadeIn("slow");
});
$("a#delete").click(function(){
$('.galerry ul li[id="'+ delid +'"]').css('background','red');
$.post(url,{action:'del_images',image:delid},function(){
window.setTimeout(function(){
$('.galery ul li[id="'+ delid +'"]').fadeOut("slow");
},500);
$('.delete').fadeOut("fast",function(){
$('.delete_dialog').fadeOut("fast");
});
});
$("a#toggleDialog").click(function(){
$('.delete').fadeOut("fast",function(){
$('.delete_dialog').fadeOut("fast");
});
});
});
Add some identificators to you "Yes/No" links (ids, attributes or something else):
<div class="delete_dialog">
<div class="delete">
<p>Do you really want to delete this image?</p>
Yes
No
</div>
</div>
Add handler to links like:
$("a#delete").click(function(){
//your post method
});
$("a#toggleDialog").click(function(){
//hide dialog
});
Change your open dialog handler to show dialog only:
$('.galery ul').on('click','.galerydel',function(){
var delid = $(this).attr('id');
$('.delete_dialog').fadeIn("slow",function(){
('.delete').fadeIn("slow");
});
});
P.S. also you should pass the delid variable to "Yes" handler.
How to reload div (without refresh the page) with different values?
I have this code:
$value1 = 'value1';
jQuery(document).ready(function($){
$('#content').doSomthing({
string: {
id: '<?php echo $value1; ?>'
}
});
<div id="content"></div>
<a onclick"">replace with value 2<a/> //when press this the id will be 'value2'
I dont mind to use only jquery if i need to, but what way i need to do this?
are you looking for this,
<script>
$(document).ready(function () {
$('#anchor').click(function () {
$("#content").html($(this).html());
});
});
</script>
<div id="content">
</div>
<a id="anchor">replace with value 2<a />
Try this:
$("a").click(function(e){
e.preventDefault(); //stop page refreshing
var value = this.innerHTML.match(/value \d+/);
if(value){
value = value[0];
$('#content').html(value);
}
});
You better assign a class to that anchor element and register the click event as $("a.className").
I want to get selected text from android phonegap. I have some text in htmlpage when i selected some text i want to get it back and change the color of selected text.But i am unable to select text. My text data is in div.Please help me. Here is my code.
<body>
<div data-role="page">
<div data-role="content">
</div>
<div id="log">
</div>
</body>
<script>
$.ajax({
type:'GET',
url: 'http://10.0.2.2:7080/example/TranscriptVieww',
dataType:'text',
success: function(data){
$( "#log" ).append(data);
},
error: function(){
alert("There was an error loading the data.");
}
});
</script>
This will work in a browser but not sure about mobile webview. Give it a shot:
function GetSelectedText () {
if (window.getSelection) {
var range = window.getSelection ();
//range is the selected text
}
}
Wait... Are you talking about user selected text, programmatically selected text, or just all the text from the "log" div? The above will work for user selected and programmatically selected text but not getting all content from a div. If you just want all content from the log div just do a simple innerHTML call:
var selectedText = document.getElementById('log').innerHTML;
you can use this javascript method to get selected content from any page.
var selectedText = getselectedcontent();
alert(selectedText);
--------------------------------
function getselectedcontent() {
var selection = window.getSelection();
var range = selection.getRangeAt(0);
if (range) {
var div = document.createElement('div');
div.appendChild(range.cloneContents());
return div.innerHTML;
} else {
return "";
}
}