Edit DIVs after .append() - php

My algorithm:
I get the DIV text from php/SQL ($.get( "read.php"...)
APPEND contenteditable div with loaded text by jQuery
check the div value, if there is errors in text I make div red (assign class, $(this).addClass("fill_red");)
on every change of text - check and assign/remove class if needed.
Problem is: with preloaded text - everything is working.
But when I append div using JS - check function don't works.
I searched the web, maybe on() method helps me.
But what event?
It should be something like onload, onchange..?
(yes, I could make div generated by php and solve the problem, but I dont want full refresh)
Thank you!
part of code:
//texts load
$(function() {
$.get( "read.php", function( data ) {
var ionka = data.split(' ');
ionka.forEach(function(item, i, arr) {
var app_text = "<div id=\"segm" + i + "\" contenteditable role=\"textbox\">" + item + "</div>";
$("#textarea").append(app_text);
});
});
//checks
var intRegex = new RegExp('^[0-9/\]{5}$');
$('#textarea div').each(function(i,elem) {
if(!intRegex.test($(this).text())) {
$(this).addClass("fill_red");
}else{
$(this).removeClass();
}
});
// edit on change. Blur because of contenteditable
var segm_array = [];
$('#textarea div').each(function(i,elem) {
$(this).blur(function() {
if (segm_array[i]!=$(this).text()){
segm_array[i] = $(this).text();
if(!intRegex.test(segm_array[i])) {
$(this).addClass("fill_red");
}else{
$(this).removeClass();
}
}
});
});

You dont show much code here, but my guess is that you are trying to add class before new data is loaded into dom
$.get( "read.php" ).done(function( data ) {
// addClass etc
});

Related

If Jquery variable equals the class of a div then set display to block

I'm outputting several divs using php - each div has a different country name for the class.
I'm also outputting a variable using jquery which checks if content of a div has changed. That variable will also be a country name.
If the jquery variable matches a div class, I want that div to .show(), how can I do that?
This is my (horrible) attempt:
(function($) {
$(document).ready(function () {
$("#block1").bind("DOMSubtreeModified", function() {
message = $("#block1").html();
regiondiv = '.';
fullregion = regiondiv + message;
alert(fullregion);
if ($('.region-logos').hasClass(message)) {
$(fullregion).show();
} else {
$(fullregion).hide();
}
});
});
})(jQuery);
If I click on Canada for instance, it will show the .Canada div, but if I click on Spain after it, it's shows the .Spain div as well as the .Canada div. I.e once you click on more than one it just continues to show them all. It doesn't hide the divs if you haven't click on it.
var class = 'no-class';
$(document).ready(function () {
$("#block1").bind("DOMSubtreeModified", function() {
var regiondiv = '.';
var fullregion = regiondiv + class ;
$(".fullregion").hide();
class = $("#block1").html();
fullregion = regiondiv + class ;
$(".fullregion").show();
});
});
Not sure if I followed the question correctly. I assume you want to display a div if class of that div matches a variable in javascript. If so the you can try this:
(function($) {
$(document).ready(function () {
$("body").bind("DOMSubtreeModified", function() {
// Not sure how are you generating this jquery variable
var yourJqueryVariable;
// Check if class name exists
if ($(".yourJqueryVariable")[0]){
$(".yourJqueryVariable").show(); //or even $(".yourJqueryVariable").css('display','block');
}
});
});
})(jQuery);
(function($) {
$(document).ready(function () {
$("#block1").bind("DOMSubtreeModified", function() {
var message = $("#block1").html();
//ok so you have the variable to check
if($('.'+message).length > )) { //is there 1 or more of these classes in the DOM?
$('.'+message).each(function() { //there is, loop and show them all
$(this).show();
});
}
});
});
})(jQuery);
EDIT
Ok looking at your updated answer, assuming there are multiple .region-logos you need to perform your if else within a loop of those:
$('.region-logos').each(function() {
if($(this).hasClass(message)) {
$(fullregion).show();
}else {
$(fullregion).hide();
}
});

Jquery selector not working after append

I have a php script that I call that returns html in a way that it can be directly inserted into a container or the body and just work (E.X. '<image id="trolleyLogoEdge" class="pictureFrame party" src="tipsyTrixy.png" >'). After appending this text to a div the selector $('#pictureFrame > img:first') won't work. I'm not using event handlers or anything so I don't know why I'm having an issue. My code worked fine when I just had the image tags in the div without any manipulation so I'm assuming it must be a selector issue. I have tested my php output and it is exactly matching the html that was in the div before I decided to dynamically populate the div.
var classType = '';
var classTypePrev = '';
var width = $(window).width();
var height = $(window).height();
var size = (height + width)/2;
var time = 0;
$( document ).ready(function()
{
$.post( "pictureDirectory.php", function( data )
{
$('#picureFrame').append(data);
startSlideshow($('#pictureFrame > img:first'));
});
});
window.onresize = function()
{
width = $(window).width();
};
function startSlideshow(myobj)
{
classType = $(myobj).attr('class').split(' ')[1];
if(classTypePrev != classType)
{
$('.picDescription').animate({'opacity': "0"},{duration: 2000,complete: function() {}});
$('.picDescription.' + classType).animate({'opacity': "1"},{duration: 3000,complete: function() {}});
}
classTypePrev = classType;
myobj.animate({left: "-=" + ((width/2)+ ($(myobj).width()/2) - 150), opacity: '1'},{
duration: 5000,
'easing': 'easeInOutCubic',
complete: function() {}}).delay(2000).animate({left: "-=" + ((width/2)+ ($(myobj).width()/2) + 150), opacity: '0'},{
duration: 5000,
'easing': 'easeInOutCubic',
complete: function()
{
$(myobj).css("left", "100%");
}
});
setTimeout(function()
{
var next = $(myobj).next();
if (!next.length)
{
next = myobj.siblings().first();
}
startSlideshow(next)},9000);
}
Your code that appends the data to the frame has a typo in the ID selector.
$.post( "pictureDirectory.php", function( data )
{
$('#picureFrame').append(data);
^^here
startSlideshow($('#pictureFrame > img:first'));
});
It should probably be
$('#pictureFrame').append(data);
.find() gets the descendants of each element in the current set of matched elements.
> selects all direct child elements specified by "child" of elements specified by "parent".
Try:
startSlideshow($("#pictureFrame").find("img:first"));
If img is not direct child of #pictureFrame, .find() should work.
You should know the difference between
Delegated Event
Direct Event
check this for the difference between direct and delegated events.
If we were to click our newly added item, nothing would happen. This is because of the directly bound event handler that we attached previously. Direct events are only attached to elements at the time the .on() method is called. In this case, since our new anchor did not exist when .on() was called, it does not get the event handler.
check this link to official JQuery Document for further clarification.

Creating dynamic div content with jquery

I'm looking to put a div on my website where the content changes based on what link is clicked without refreshing. The content to put there comes from a MySQL database and it's put in JSON.
My problem is that I can't get the JSON data to display when clicking the links.
Here's the script I'm using:
$(document).ready(function () {
$.getJSON("jsondata.php",rightSideData);
function rightSideData(data) {
for(var i=0; i<data.length;i++) {
$("#changetext"+data[i].id).click(function() {
$("#rightside").html("<h1>" + data[i].title + "</h1><p />" + data[i].content);
});
}
}
});
This is the div element that has to change:
<div class='rightside' id='rightside'>Test</div>
The links are constructed this way:
echo "<a id='changetext" . $row['id'] . "'> ";
echo "<div class='tile'>";
echo "<h2>Tile</h2></div></a>";
I've tested the different elements and they work fine (changing the divs content with hardcoded data, displaying the JSON data), but I'm having a hard time figuring out why the combined thing isn't working.
Objects does'nt have a length, use $.each to iterate it instead, unless it's actually an array containing objects :
$(document).ready(function () {
$.getJSON("jsondata.php",rightSideData);
function rightSideData(data) {
$.each(data, function(i, d) {
$("#changetext" + d.id).on('click', function() {
var h1 = $('<h1 />', {text : d.title}),
p = $('<p />', {text : d.content});
$("#rightside").html(h1.add(p));
});
});
}
});
The problem is that i var will be data.length at the end of the loop and that's what the click handler will see.

ie and jquery $.get not working

I am trying to update the content of a div with a $.get call but it is failing in ie(9).
the js is this
function UpdateElementOfParent(box_id, page_ref, template_ref)
{
$.get("get_content.php", { box_id: box_id, page_ref: page_ref, template_ref:template_ref } )
.done(function(data) {
$('#'+box_id).html(data);
});
}
and the get_content.php is this
<?php
include("connect.php");
$page_ref = $_GET['page_ref'];
$template_ref = $_GET['template_ref'];
$box_id = $_GET['box_id'];
$sql = mysql_query("SELECT * FROM site_content WHERE page_ref='$page_ref' AND template_ref='$template_ref' AND box_id='$box_id' AND box_type='text'");
while($row=mysql_fetch_array($sql))
{
echo stripslashes($row['content']);
}
?>
it works fine in firefox/chrome/safari and opera.
the php updates the db but the div ("#"+box_id) doesnt update in ie (only have ie9 at hand so dont know if its just 9 or other versions also)
any clues?
QUICK UPDATE
it seems that ie is holding some data from a previous $.get call in the cache. Basically I have a div on the screen and when the user clicks a button, a layer opens with a textarea that is editable with nicedit.
The textarea is populated with a $.get, then the user clicks save, the layer is hidden and the original div on the parent page is updated with the same $.get call.
In ie, if I change the content, the db is updated but the div is not and when I open the layer, it still shows the old data.
the first $.get call is this
$.get("get_content.php", { box_id: box_id, page_ref: page_ref, template_ref:template_ref } )
.done(function(data) {
document.getElementById("edit_content").value=data;
area1 = new nicEditor({fullPanel : true}).panelInstance("edit_content",{hasPanel : true});
});
the alerted data doesnt show the updated text in IE so its definately something to do with the $.get call
I figured out the problem. Nothing to do with the selector, but with the scope of the parameter variable box_id.
Change your function to:
function UpdateElementOfParent(box_id, page_ref, template_ref) {
myBox = box_id;
$.get("get_content.php", { box_id: box_id, page_ref: page_ref, template_ref:template_ref })
.done(function(data) {
$('#'+myBox).html(data);
});
}
Explanation:
The AJAX callback function does not have access to the local variable in UpdateElementOfParent
This isn't an answer, as the question is incomplete, but I need to post a code comment to assist OP.
As you mentioned that the PHP works just fine, the problem might be that IE doesn't like dynamic selectors in jQuery. Do try these few options:
1) Change $('#'+box_id).html(data); to:
var id = '#'+box_id;
$(id).html(data);
2) Try logging or alert-ing the element out, to see if IE actually got the element right:
var elem = $('#'+box_id);
alert(elem);
elem.html(data);
This would display as [HTMLDivElement] or something similar if the element is there.
3) If all else fails, see if this vanilla JS works in IE, to verify that it isn't a jQuery selector problem.
var elem = document.getElementById(box_id);
alert(elem);
elem.innerHTML = data;
ok problem solved and I knew it was something very obvious.
inside the original $.get function call I have to set the document.ready state
function get_edit_content(box_id,page_ref,template_ref)
{
$(document).ready(function() { <<<<<HERE
if(area1) {
area1.removeInstance('edit_content');
area1 = null;
document.getElementById("edit_content").value="";
}
$.get("get_content.php", { box_id: box_id, page_ref: page_ref, template_ref:template_ref } )
.done(function(data) {
document.getElementById("edit_content").value=data;
document.getElementById("page_ref").value=page_ref;
document.getElementById("template_ref").value=template_ref;
document.getElementById("box_id").value = box_id;
area1 = new nicEditor({fullPanel : true}).panelInstance("edit_content",{hasPanel : true});
});
});
}
thanks for all the input

Jquery replaceWith:replace one php file with another php file based on screen resolution

I need to be able to replace a php file with another php file based on screen resolution. This is what I have so far:
<script type="text/javascript">
function adjustStyle(width) {
width = parseInt(width);
if (width = 1920) {
$('book.php').replaceWith('book2.php');
}
}
$(function() {
adjustStyle($(this).width());
$(window).resize(function() {
adjustStyle($(this).width());
});
});
</script>
which obviously isn't working-- any ideas? Thank you in advance for any help received.
UPDATE
Is this at all close (to replace the book.php line)?
{ $("a[href*='book.php']").replaceWith('href', 'book2.php'); };
Second Update to reflect input gathered here
function adjustStyle(width) {
width = parseInt(width);
if (width == 1920) {
$('#bookinfo').replaceWith(['book2.php']);
$.ajax({
url: "book2.php",
}).success(function ( data ) {
$('#bookinfo').replaceWith(data);
});
$(function() {
adjustStyle($(this).width());
$(window).resize(function() {
adjustStyle($(this).width());
});
});
}
}
I have not seen the use of replaceWith in the context you put it in. Interpreting that you want to exchange the content, you may want to do so my using the load() function of jQuery.
if(width == 1920){
$("#myDiv").load("book1.php");
} else {
$("#myDiv").load("book2.php");
}
Clicking on the button replaces the content of the div to book2.php.
The first problem is I don't think that you are using the correct selectors. If you have the following container:
<div id="bookContainer">Contents of book1.php</div>
The code to replace the contents of that container should be
$('#bookContainer').replaceWith([contents of book2.php]);
In order to get [contents of book2.php] you will need to pull it in by ajax using the following code I have also included the line above so that the data from book2.php will be placed into the container:
$.ajax({
url: "http://yoururl.com/book2.php",
}).success(function ( data ) {
$('#bookContainer').replaceWith(data);
});.
I haven't tested this so there might be an issue but this is the concept you need to accomplish this.
First off... using a conditional with a single = (equal sign) will cause the condition to always be true while setting the value of variable your checking to the value your checking against.
Your condition should look like the following...
if (width == 1920) { // do something }
Second, please refer to the jQuery documentation for how to replace the entire tag with a jquery object using replaceWith()... http://api.jquery.com/replaceWith/
I would use a shorthand POST with http://api.jquery.com/jQuery.post/ since you don't have the object loaded yet...
In short, my code would look like the following using $.post instead of $.ajax assuming I had a tag with the id of "book" that originally has the contents of book.php and I wanted to replace it with the contents of book2.php...
HTML
<div id="book">*Contents of book.php*</div>
jQuery
function onResize(width) {
if (parseInt(width) >= 1920) {
$.post('book2.php',function(html){
$('#book').html(html).width(width);
});
}
else {
$.post('book.php',function(html){
$('#book').html(html).width(width);
});
}
}
Hope this helps.

Categories