Display image one by one - image

I have a checkbox in my form that will display images when an item is checked .
Is it possible that the images will be displayed one by one every time an item is clicked because at the moment , every time I checked an item on the checkbox , it is displayed on the div that I assigned .
What I want to achieve is , when an item is checked , it will be displayed and when I clicked another item , the previous image will be overridden by the new item that was checked .
I assigned an ID and class in the image and here is my JS :
jQuery(document).ready(function( $ ){
$(function() {
$('.decalcheckbox input[type=checkbox]').on("change",function() {
var checkbox = $(this).val().toLowerCase();
var checkboxremovespace = checkbox.replace(/ /g, "_")
$('#decal_'+ checkboxremovespace).toggle(this.checked);
}).change(
); // trigger the change
});
});
Sorry for my English but I hope I explained what I want to say .
Thanks .

I just made some modification on my code as follows .
Hopefully someone can shed some light .
jQuery(document).ready(function( $ ){
$(function() {
$('.decalcheckbox input[type=checkbox]').on("change",function() {
if ($(this).is(':checked')) {
$("#bento_preview_item").hide();
}
else{
$("#bento_preview_item").show();
}
var checkbox = $(this).val().toLowerCase();
var checkboxremovespace = checkbox.replace(/ /g, "_")
$('#decal_'+ checkboxremovespace).toggle(this.checked);
}).change(
); // trigger the change
});
});
Thanks .

Related

Update contents of select2 control and reselect previous selections

I've created a site for sharing some old family letters. I'm using two Select2 controls to let people filter who wrote the letters and who received them. It's all working nicely, but I'd like to have each select2 get filtered based on what was selected in the other one. That is, if a user chooses a particular letter writer, then I'd like the select2 of recipients to show only people that letter writer wrote to. I've actually got that part working, but updating the contents of the dropdown removes any selections it had, and I can't get updating the selections to work.
A few notes and then I'll show some code and try to clarify what I'm seeing and trying.
Both select2 controls are set up for multiple selection.
There's a MySQL database that contains the information about what letters exist, who they were written by, and who they were sent to.
The HTML for the two select2 dropdowns is quite similar. Here's the code for the "From" dropdown:
<select id="from" class="js-example-basic-multiple" multiple="multiple" style="width: 100%">
<?php
echo GetPeople('F');
?>
</select>
GetPeople is a PHP function that calls out to the database and then converts the returned data to a series of lines. The parameter indicates whether to get the "From" data or the "To" data. That parameter is also used as part of the ID for each item (because it turns out that if options with the same ID appear in different select2 controls, things go downhill fast).
function GetPeople ($type) {
$people = getdata("GetPeople", "'$type',''", "Couldn't retrieve list of people.<br/>");
$return = '';
while ($obj = mysqli_fetch_object($people)) {
$return .= "<option value='" . $obj->FullName . "' id='" . $type . $obj->iid . "'>" . $obj->FullName . "</option>";
}
return $return;
}
The OnChange event for each of the select2 controls calls a JS function called updatePeople, passing either 'F' or 'T' to indicate which select2 needs its contents updated. That is, the From dropdown passes 'T' and the To dropdown passes 'F'.
updatePeople uses AJAX to go out and collect the data, build a new set of lines and sub them into the specified control. That's all working as expected. But doing so leaves that control with no items selected. When I try to restore the selections the control had before the update, nothing happens. Here's the code for updatePeople, including my attempt to restore the selection:
function updatePeople(cwhich) {
var results = '';
var success = false;
//get the currently selected list for the other dropdown, too
//so we can use them to restore selections later
if (cwhich == "F") {
var chosen = getChoices('#to');
var selecteditems = getChoices('#from',true);
} else {
var chosen = getChoices('#from');
var selecteditems = getChoices('#to',true);
}
var filters = cwhich + "','" + chosen + "'";
var fnargs = "GetPeople|'" + filters;
$.ajax({
url: 'retrievedata.php',
type: "POST",
async: false,
data: {"functionname": "getpeople", "arguments": fnargs},
dataType: "JSON",
success: function (obj) {
if (cwhich=="F") {
var target = "#from";
} else {
var target = "#to";
}
if ((obj===null)) {
//clear dropdown
$(target).html('');
}
else {
//build the list of options
var options = '';
for (line = 0; line < obj.length; line++) {
options += "<option value='" + obj[line].FullName + "' id='" + cwhich + obj[line].iid + "'>" + obj[line].FullName + "</option>";
}
window.allowupdate = false;
$(target).html(options);
//turn list of selected items into array
var arrSelected = selecteditems.split(',');
$(target).val(arrSelected);
$(target).trigger('change');
window.allowupdate = true;
}
success = true;
},
error: function (textStatus, errorThrown) {
success = false;
$("#testresult").text('Error occurred: '.textStatus);
console.log('Error occurred: '.textStatus);
}
});
}
The window.allowupdate bit is because trying to change the selections for one dropdown would fire its OnChange, and that would change the first one. So I added a flag that's checked in the OnChange code, so that I can change one without changing the other.
What I'm looking for is how to set the modified select2 control to have the same items selected as before updating the contents of the control. TIA
Solved my own problem. There were two issues:
Setting the control’s HTML seemed to make it unhappy. I changed that code to first disconnect from select2, then update the HTML, then reconnect to select2:
$(target).select2('destroy');
$(target).html(options);
$(target).select2({placeholder: 'Anyone (or choose senders)'});
I didn’t have the right value to reset the selections. My code was retrieving the primary keys for the selected items, but I needed their actual contents, which I was able to retrieve by calling the control’s val function.

Tumblr 'loading more' button

In the first place I want to say sorry for my bad english . I'm trying to develop a tumblr theme , and add a 'loading more' button . I used JavaScript to determinate the current page and the next one . When 'Loading More' button is pressed , I use jQuery to make a request to next tumblr page ex ( sitename.tumblr.ro/page/next-page ) , get the html , extract the posts html and append it to current page . But the problem is that the like button is not working on the appended posts . When I click the button , noting is happening . The cursor is not even pointing ... Here's my javascript code :
var $holder = $('div.posts_holder');
var page = null;
$(document).on('click','div.loading_more.loading_trigger',function(){
if(page == null)
{
page = window.location.href.search('page') > -1 ? window.location.href.split('/')[window.location.href.split('/').length-1] : 1;
}
page = Number(page)+1;
$(this).text('Please Wait..');
var load_page = '{BlogURL}page/'+page;
var $saved = $(this);
//get the page
$.get(load_page,function(response)
{
var $append_html = $(response).find('div.posts_holder');
if($append_html.html().replace(' ','').trim() == '')
{
$saved.removeClass('loading_trigger');
}
$saved.text('Loading More');
$holder.append($append_html.html()).masonry();
$holder.masonry( 'reloadItems' );
$holder.masonry( 'layout' );
setTimeout(function(){
$holder.masonry( 'reloadItems' );
$holder.masonry( 'layout' );
},800);
});
});
I found the answer . You must add :Tumblr.LikeButton.get_status_by_page(page); to your javascript after you added new items ,where 'page' is the number of page you just added.

Global Expand/ collapse button for jqGrid with subgrids

I am using jqGRid with subgrid configuration to display my data. I would like to have global expand & collapse button to display or hide all subgrid information. Does jqGrid library provide this feature by any means?
jqGrid has no "Expand/Collapse all". I modified the demo from the old answer which demonstrates creating on grid with local subgrids. The resulting demo you can see here:
and it has additional "+" button in the column header of "subgrids" column. If one clicks on the button all subgrids will be expanded:
I used the following code in the demo:
var subGridOptions = $grid.jqGrid("getGridParam", "subGridOptions"),
plusIcon = subGridOptions.plusicon,
minusIcon = subGridOptions.minusicon,
expandAllTitle = "Expand all subgrids",
collapseAllTitle = "Collapse all subgrids";
$("#jqgh_" + $grid[0].id + "_subgrid")
.html('<a style="cursor: pointer;"><span class="ui-icon ' + plusIcon +
'" title="' + expandAllTitle + '"></span></a>')
.click(function () {
var $spanIcon = $(this).find(">a>span"),
$body = $(this).closest(".ui-jqgrid-view")
.find(">.ui-jqgrid-bdiv>div>.ui-jqgrid-btable>tbody");
if ($spanIcon.hasClass(plusIcon)) {
$spanIcon.removeClass(plusIcon)
.addClass(minusIcon)
.attr("title", collapseAllTitle);
$body.find(">tr.jqgrow>td.sgcollapsed")
.click();
} else {
$spanIcon.removeClass(minusIcon)
.addClass(plusIcon)
.attr("title", expandAllTitle);
$body.find(">tr.jqgrow>td.sgexpanded")
.click();
}
});
You can simply make it to behave like as toggle as follows.
Take a button.
onlick of it call the function, say toggleSubgrid();
function toggleSubgrid(){
if($('#YOURGRIDID td').hasClass('sgexpanded')){
$('.ui-icon-minus').trigger('click');
}
else if($('#YOURGRIDID td').hasClass('sgcollapsed')){
$('.ui-icon-plus').trigger('click');
}
}
This will work for all rows that are already loaded. You might need to scope the selector a bit, as fits your needs.
function expandAll () {
$( ".tree-plus" ).click();
};
function collapseAll () {
$( ".tree-minus" ).click();
};

google map infowindow's button's onclick function won't perform jquery ajax function correctly. closure or scope error?

i have a database where each row has lat/long info for goggle maps.
each row subsequently gets turned into a marker. when i click on that marker, an info window pops up.
i want the info window to have a button so that when clicked, the entry from the database will get deleted. but my button won't work. specifically, something about the eraseEntry() function attached to the onClick event isn't working. when i click the button, only the last entry of the database gets deleted, regardless of which marker i click.
var map=//make the google map
var markersArray = [];
var infoWindow = new google.maps.InfoWindow({content: ""});
var markers;
$.get("phpsqlajax_genxml.php", function(data)
{
markers = data.documentElement.getElementsByTagName("marker");
makeMarkersWithXMLinfo();
});
function makeMarkersWithXMLinfo()
{
for (var i = 0; i < markers.length; i++)
{
var name = markers[i].getAttribute("name");
var markerLocation = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" +
"</b> <br/>" + "</b> <br/>" +
"<input type='button' value='Erase Entry' onclick='eraseEntry()'/>";
var markerWithLocation = new google.maps.Marker({position: markerLocation, map: map});
var markerWithInfo = createMarker(markerWithLocation,html);
eraseEntry = function ()
{
$.get("delete.php", { identifierVar: name } );
}
}
}
function createMarker(markerWithLocation, html) {
var markerWithInfo = google.maps.event.addListener(markerWithLocation, 'click', function(){infoWindow.setContent(html); infoWindow.open(map,markerWithLocation)});
return markerWithInfo;
}
i'm able to pull from the database and create the markers just fine.
i've tried having the eraseEntry() function call another function that's outside of the makeMarkersWithXMLinf() function, but i still get the same problem. depending where i put/call those functions, sometimes javascript doesn't even think my function exists...
below's my delete.php file
<?php
require("phpsqlajax_dbinfo.php");
// Opens a connection to a MySQL server
$connection = mysql_connect ('localhost', $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
if(isset($_GET['identifierVar']))
{
$query = 'DELETE FROM markers WHERE name = '.(int)$_GET['identifierVar'];
$result = mysql_query($query);
}
?>
i've been testing with just unique names.
like 111, 222, 333.. etc
any help's appreciated. thanks.
identifierVar should be identifierId, where identifierId is the id of that marker. try making these delete queries with the id, its much faster and it's a unique value.
your query is probably like this: delete from x where name = '$name'. you need to limit to 1, like: delete from x where name = '$name' limit 1
after you've successfully deleted the marker from database, delete it off the map
use firebug always in your debugging

CKEditor: Customized HTML on inserting an image

I'm using CKEditor 3.5 to provide WYSYWYG editing in a website. When inserting an image you can provide width and height of the image, which results in HTML like follows:
<img alt="" src="/Images/Sample.png" style="width: 62px; height: 30px; " />
Since this does the resizing in the browser and in other places on the same website I use Nathanael Jones' Image Resizing Module, I'd like to get the following output instead:
<img alt="" src="Images/Sample.png?width=62&height=30" />
Is there an easy way to control the generated HTML or have I really to write my own dialog/plugin for CKEditor?
EDIT:
Adding the following lines to config.js was the solution that eventually worked for me:
CKEDITOR.on('dialogDefinition', function (ev) {
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
var dialog = dialogDefinition.dialog;
var editor = ev.editor;
if (dialogName == 'image') {
dialogDefinition.onOk = function (e) {
var imageSrcUrl = e.sender.originalElement.$.src;
var width = e.sender.originalElement.$.width;
var height = e.sender.originalElement.$.height;
var imgHtml = CKEDITOR.dom.element.createFromHtml('<img src=' + imageSrcUrl + '?width=' + width + '&height=' + height + ' alt="" />');
editor.insertElement(imgHtml);
};
}
});
The next problem is then, when editing an image, the width and height naturally are in the URL field and are missing in the dedicated fields for width and height. So I need to come up with a solution for the reverse... :-)
I kind of had the same problem, I needed to remove those attributes from the generated HTML for the image, so what I did was to override the onOK method of the uploader and insert the image element manually using the CKEditor's API, something like this:
CKEDITOR.on('dialogDefinition', function(ev) {
// Take the dialog name and its definition from the event data
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
var editor = ev.editor;
if (dialogName == 'image') {
dialogDefinition.onOk = function(e) {
var imageSrcUrl = e.sender.originalElement.$.src;
var imgHtml = CKEDITOR.dom.element.createFromHtml("<img src=" + imageSrcUrl + " alt='' align='right'/>");
editor.insertElement(imgHtml);
};
}
}
This has worked for us so far.
Look at the "output html" sample, you can find there some code that changes the dimensions in images from styles to attributes, so you can adjust it to rewrite the URL.
I don't have enough points to comment on that previous answer. but in respect to your error: CKEDITOR.currentInstance returns undefined.
That is strange because CKEDITOR is global, but you shouldn't have to resort to that.
Within the OK function invocation, you have access to "editor", you shouldn't have to get the instance.
just a suggestion.
Best bet might be to "recreate" the src (and possibly the style) field's behavior. I've do something similar. (but not as complex)
Start with the original code (from plugins/dialog/image.js) and create setup and commit logic that produces (and parses) the markup you're looking for.
Then during dialog definition
Delete Originals
Add your "custom" fields
style field not sure, maybe just leave it in the dialog, but stub out it's commit logic.
I added my field to the dialog...
var infoTab = dialogDefinition.getContents( 'info' );
// Move the ID field from "advanced" to "info" tab.
infoTab.add( idField_config);
var idField_config = {
type : 'text',
label : 'Name',
id : 'linkId',
setup : function( type, element ) {
//if ( type == IMAGE )
this.setValue( element.getAttribute( 'id' ) );
},
commit : function( type, element ) {
//if ( type == IMAGE ) {
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'id', this.getValue() );
//}
}
};
Issues I faced.
New fields get added to end of
dialog.
Pieces of the original code
( type == IMAGE ) isn't valid (Love to know why but felt comfortable it was safe to comment for my usage)
You might face problems with the markup rules undoing your hard work, but "output html" sample" suggestion should help you weed through that issue.

Resources