I used bootstrap 3 tabs in php but when i refresh my previous tab forms fields shown empty,How i show these fields after refreshing page?
Here is my code:
var hash = window.location.hash;
$('#signup_tabs_group a[href="' + hash + '"]').tab('show');
// Get form data and enforce tab wise validation
var form_data = $.parseJSON($('form').attr('data-elements'));
$("#continue_to_account").click(function (e) {
if ($("#password1").val() != '' && $("#password1").val() != $("#password2").val()) {
popoverContent('password2', "Please Confirm Password.", "right");
$("#password2").popover('show');
$("#password2").addClass('mypopover');
$("#password2").focus();
return false;
} else {
$("#password2.mypopover").popover('hide');
}
if ($("#email").val() != '' && $("#email").val() != $("#email2").val()) {
popoverContent ('email2', "Please Confirm Email.", "right");
$("#email2").popover('show');
$("#email2").focus();
$("#email2").addClass('mypopover');
return false;
} else {
$("#email2.mypopover").popover('hide');
}
$("ul.nav-tabs > li > a").on("shown.bs.tab", function (e) {
var id = $(e.target).attr("href").substr(1);
window.location.hash = id;
});
var custom_form = [];
var required_elements = ['email', 'email2', 'username', 'password1', 'password2'];
for (var c = 0; c < form_data.length; c++) {
if (typeof(form_data[c].name) != "undefined" && required_elements.indexOf(form_data[c].name) != -1) {
custom_form[c] = form_data[c];
}
}
if (validations(custom_form, $('form'), $(this), 'right') != false) {
e.preventDefault();
$('#signup_tabs_group a[href="#contact"]').tab('show');
return true;
}
return false;
});
$("#back_to_account").click(function (e) {
e.preventDefault();
$('#signup_tabs_group a[href="#account"]').tab('show');
});
$("#continue_to_website").click(function (e) {
var custom_form = [];
var required_elements = [{'contact_first_name': true}, {'contact_last_name': true}, {'country': true}, {'account_type': true}, {'address1': true}, {'address2': false}, {'address3': false}, {'city': true}, {'state': false}, {'zipcode': true}, {'phone_code': false}, {'phone_number': true}, {'fax': false}, {'currency': false}];
if (
typeof($('input[name=account_type]:checked').val()) != 'undefined' &&
$('input[name=account_type]:checked').val() == 'company'
) {
required_elements.push({'company_name': true});
}
//return false;
for (var c = 0; c < form_data.length; c++) {
if (
typeof(form_data[c].name) != "undefined" &&
typeof(form_data[c].validation) != "undefined" &&
typeof(form_data[c].validation.required) != "undefined"
) {
for (var i = 0; i < required_elements.length; i++) {
if (typeof(required_elements[i][form_data[c].name]) != 'undefined') {
form_data[c].validation.required = required_elements[i][form_data[c].name];
custom_form[c] = form_data[c];
break;
}
}
}
}
if (validations(custom_form, $('form'), $(this), 'right') != false) {
e.preventDefault();
$('#signup_tabs_group a[href="#website"]').tab('show');
return true;
}
return false;
});
$("#back_to_website").click(function (e) {
e.preventDefault();
$('#signup_tabs_group a[href="#contact"]').tab('show');
});
$('input[name=account_type]').change(function() {
if ($('input[name=account_type]:checked').val() == 'company') {
$('.company-label').removeClass('hidden');
} else {
$('.company-label').addClass('hidden');
$('#company_name').val('');
if ($('#company_name').hasClass('mypopover')) {
$('#company_name').popover('hide');
$('#company_name').popover('disable');
}
}
});
// jQuery International Telephone Input With Flags and Dial Codes
$("#phone_code").intlTelInput({
defaultCountry: "gb"
});
//Validation
$(".validate_button").click(function(e){
var words = $('#description').val().split(/\b[\s,\.-:;]*/);
if (words.length > 100) {
words.splice(100);
$('#description').val(words.join(" "));
}
var custom_form3 = [];
var required_elements = ['website_name', 'website_url', 'unique_visitors', 'audience_geo', 'audience_interests', 'website_content', 'advertising_type', 'other_affiliate_member', 'working_with_qs', 'description', 'hear_about_us', 'accept_terms'];
for (var c = 0; c < form_data.length; c++) {
if (typeof(form_data[c]) != "undefined" && typeof(form_data[c].name) != "undefined" && required_elements.indexOf(form_data[c].name) != -1) {
custom_form3[c] = form_data[c];
}
}
if (validations(custom_form3, $('form'), $(this), 'right') != false) {
return true;
}
How i show form fields after refreshing page?
It's rather pure JS/jQuery question than ZF2 related.
I solved this problem in such a way:
$(function(){
var url = document.location.toString();
if (url.match('#')) {
$('.nav-tabs a[href=#'+url.split('#')[1]+']').tab('show') ;
}
$('.nav-tabs a').on('shown.bs.tab', function (e) {
window.location.hash = e.target.hash;
});
});
i'm looking for tabs which 'a' element href ends with hash from url and then i show them. I also set in window url hash component when someone click on tab so after that someone refresh page it bring him last viewed tab.
Related
I downloaded one jquery crop image module it is working fine,actually i want now that original image value,from this code i got only for cropped image value,when i upload one image means i want store that image in without crop,actually i don't know how to get that value in this code reference URL http://fengyuanchen.github.io/cropper/v1.0.0/
$(function () {
'use strict';
var console = window.console || { log: function () {} };
var $body = $('body');
// Tooltip
// $('[data-toggle="tooltip"]').tooltip();
// $.fn.tooltip.noConflict();
// $body.tooltip();
// Demo
// ---------------------------------------------------------------------------
(function () {
var $image = $('.img-container > img');
console.log($image);
var $actions = $('.docs-actions');
var $download = $('#download');
//console.log($download);
var $dataX = $('#dataX');
var $dataY = $('#dataY');
var $dataHeight = $('#dataHeight');
var $dataWidth = $('#dataWidth');
var $dataRotate = $('#dataRotate');
var $dataScaleX = $('#dataScaleX');
var $dataScaleY = $('#dataScaleY');
var options = {
aspectRatio: 16 / 9,
preview: '.img-preview',
crop: function (e) {
$dataX.val(Math.round(e.x));
$dataY.val(Math.round(e.y));
$dataHeight.val(Math.round(e.height));
$dataWidth.val(Math.round(e.width));
$dataRotate.val(e.rotate);
$dataScaleX.val(e.scaleX);
$dataScaleY.val(e.scaleY);
}
};
$image.on({
'build.cropper': function (e) {
//console.log(e.type);
},
'built.cropper': function (e) {
//console.log(e.type);
},
'cropstart.cropper': function (e) {
//console.log(e.type, e.action);
},
'cropmove.cropper': function (e) {
//console.log(e.type, e.action);
},
'cropend.cropper': function (e) {
//console.log(e.type, e.action);
},
'crop.cropper': function (e) {
// console.log(e.type, e.x, e.y, e.width, e.height, e.rotate, e.scaleX, e.scaleY);
},
'zoom.cropper': function (e) {
console.log(e.type, e.ratio);
}
}).cropper(options);
// Methods
$actions.on('click', '[data-method]', function () {
var $this = $(this);
var data = $this.data();
var $target;
var result;
if ($this.prop('disabled') || $this.hasClass('disabled')) {
return;
}
if ($image.data('cropper') && data.method) {
data = $.extend({}, data); // Clone a new one
if (typeof data.target !== 'undefined') {
$target = $(data.target);
if (typeof data.option === 'undefined') {
try {
data.option = JSON.parse($target.val());
} catch (e) {
//console.log(e.message);
}
}
}
result = $image.cropper(data.method, data.option, data.secondOption);
if (data.flip === 'horizontal') {
$(this).data('option', -data.option);
}
if (data.flip === 'vertical') {
$(this).data('secondOption', -data.secondOption);
}
if (data.method === 'getCroppedCanvas' && result) {
$('#getCroppedCanvasModal').modal().find('.modal-body').html(result);
if (!$download.hasClass('disabled')) {
$download.attr('href', result.toDataURL());
console.log(result.toDataURL());//data:base64 ans
$(document).ready(function(){
$('#crop').click(function(){
//console.log('ok');
$.ajax({
type:'POST',
url: "crop_image_insert.php",
data: ({'crop': result.toDataURL()}),
success:function(data){
console.log(data);
if(data == 'SUCCESS'){
window.location.assign('php/timeline.php?id=<?php echo $ssmid;?>');
}
},
error:function(error){
alert('n');
}
});
});
});
}
}
if ($.isPlainObject(result) && $target) {
try {
$target.val(JSON.stringify(result));
} catch (e) {
}
}
}
});
// Keyboard
$body.on('keydown', function (e) {
if (!$image.data('cropper') || this.scrollTop > 300) {
return;
}
switch (e.which) {
case 37:
e.preventDefault();
$image.cropper('move', -1, 0);
break;
case 38:
e.preventDefault();
$image.cropper('move', 0, -1);
break;
case 39:
e.preventDefault();
$image.cropper('move', 1, 0);
break;
case 40:
e.preventDefault();
$image.cropper('move', 0, 1);
break;
}
});
// Import image
var $inputImage = $('#inputImage');
var URL = window.URL || window.webkitURL;
var blobURL;
if (URL) {
$inputImage.change(function () {
var files = this.files;
var file;
if (!$image.data('cropper')) {
return;
}
if (files && files.length) {
file = files[0];
if (/^image\/\w+$/.test(file.type)) {
blobURL = URL.createObjectURL(file);
$image.one('built.cropper', function () {
URL.revokeObjectURL(blobURL); // Revoke when load complete
}).cropper('reset').cropper('replace', blobURL);
$inputImage.val('');
} else {
$body.tooltip('Please choose an image file.', 'warning');
}
console.log($inputImage.val(''));
}
});
} else {
$inputImage.prop('disabled', true).parent().addClass('disabled');
}
}());
});
I have an issue, where I use jScroll for infinite scroll(jScroll), which works fine when the page loads. But the infinite scrolling is not working after an ajax call by a product filter in a search result page.
So here are my filter function called on change ajax call:
<script type='text/JavaScript'>
function filter_onchange()
{
$('#imgLoader').show();
$("#searchResults").load("<?php print $config_baseHREF; ?>search.php?ajax=1&"+$(".ajax").serialize());
$('imgLoader').hide();
}
</script>
Here is my jscroll script called from the footer.
<script>
$('.page-section').jscroll({
autotrigger: true,
loadingHtml: '<img class="center-block" src="/images/712.gif" alt="Loading" />',
padding: 20,
nextSelector: 'a.next',
contentSelector: '.infinite, .pagination',
});
</script>
So the issue is that after a user has used an filter(calling the function filter_onchange()) the jScroll stops working. In console I get the error:
TypeError: data is undefined
if (!data.waiting && iTotalHeight + _options.padding >= $inner.outerHeight()) {
jScroll.js
/*!
* jScroll - jQuery Plugin for Infinite Scrolling / Auto-Paging
* http://jscroll.com/
*
* Copyright 2011-2013, Philip Klauzinski
* http://klauzinski.com/
* Dual licensed under the MIT and GPL Version 2 licenses.
* http://jscroll.com/#license
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl-2.0.html
*
* #author Philip Klauzinski
* #version 2.3.4
* #requires jQuery v1.4.3+
* #preserve
*/
(function($) {
'use strict';
// Define the jscroll namespace and default settings
$.jscroll = {
defaults: {
debug: true,
autoTrigger: true,
autoTriggerUntil: false,
loadingHtml: '<small>Loading...</small>',
padding: 0,
nextSelector: 'a:last',
contentSelector: '',
pagingSelector: '',
callback: false
}
};
// Constructor
var jScroll = function($e, options) {
// Private vars and methods
var _data = $e.data('jscroll'),
_userOptions = (typeof options === 'function') ? { callback: options } : options,
_options = $.extend({}, $.jscroll.defaults, _userOptions, _data || {}),
_isWindow = ($e.css('overflow-y') === 'visible'),
_$next = $e.find(_options.nextSelector).first(),
_$window = $(window),
_$body = $('body'),
_$scroll = _isWindow ? _$window : $e,
_nextHref = $.trim(_$next.attr('href') + ' ' + _options.contentSelector),
// Check if a loading image is defined and preload
_preloadImage = function() {
var src = $(_options.loadingHtml).filter('img').attr('src');
if (src) {
var image = new Image();
image.src = src;
}
},
// Wrap inner content, if it isn't already
_wrapInnerContent = function() {
if (!$e.find('.jscroll-inner').length) {
$e.contents().wrapAll('<div class="jscroll-inner" />');
}
},
// Find the next link's parent, or add one, and hide it
_nextWrap = function($next) {
var $parent;
if (_options.pagingSelector) {
$next.closest(_options.pagingSelector).hide();
} else {
$parent = $next.parent().not('.jscroll-inner,.jscroll-added').addClass('jscroll-next-parent').hide();
if (!$parent.length) {
$next.wrap('<div class="jscroll-next-parent" />').parent().hide();
}
}
},
// Remove the jscroll behavior and data from an element
_destroy = function() {
return _$scroll.unbind('.jscroll')
.removeData('jscroll')
.find('.jscroll-inner').children().unwrap()
.filter('.jscroll-added').children().unwrap();
},
// Observe the scroll event for when to trigger the next load
_observe = function() {
_wrapInnerContent();
var $inner = $e.find('div.jscroll-inner').first(),
data = $e.data('jscroll'),
borderTopWidth = parseInt($e.css('borderTopWidth'), 10),
borderTopWidthInt = isNaN(borderTopWidth) ? 0 : borderTopWidth,
iContainerTop = parseInt($e.css('paddingTop'), 10) + borderTopWidthInt,
iTopHeight = _isWindow ? _$scroll.scrollTop() : $e.offset().top,
innerTop = $inner.length ? $inner.offset().top : 0,
iTotalHeight = Math.ceil(iTopHeight - innerTop + _$scroll.height() + iContainerTop);
if (!data.waiting && iTotalHeight + _options.padding >= $inner.outerHeight()) {
//data.nextHref = $.trim(data.nextHref + ' ' + _options.contentSelector);
_debug('info', 'jScroll:', $inner.outerHeight() - iTotalHeight, 'from bottom. Loading next request...');
return _load();
}
},
// Check if the href for the next set of content has been set
_checkNextHref = function(data) {
data = data || $e.data('jscroll');
if (!data || !data.nextHref) {
_debug('warn', 'jScroll: nextSelector not found - destroying');
_destroy();
return false;
} else {
_setBindings();
return true;
}
},
_setBindings = function() {
var $next = $e.find(_options.nextSelector).first();
if (!$next.length) {
return;
}
if (_options.autoTrigger && (_options.autoTriggerUntil === false || _options.autoTriggerUntil > 0)) {
_nextWrap($next);
if (_$body.height() <= _$window.height()) {
_observe();
}
_$scroll.unbind('.jscroll').bind('scroll.jscroll', function() {
return _observe();
});
if (_options.autoTriggerUntil > 0) {
_options.autoTriggerUntil--;
}
} else {
_$scroll.unbind('.jscroll');
$next.bind('click.jscroll', function() {
_nextWrap($next);
_load();
return false;
});
}
},
// Load the next set of content, if available
_load = function() {
var $inner = $e.find('div.jscroll-inner').first(),
data = $e.data('jscroll');
data.waiting = true;
$inner.append('<div class="jscroll-added" />')
.children('.jscroll-added').last()
.html('<div class="jscroll-loading">' + _options.loadingHtml + '</div>');
return $e.animate({scrollTop: $inner.outerHeight()}, 0, function() {
$inner.find('div.jscroll-added').last().load(data.nextHref, function(r, status) {
if (status === 'error') {
return _destroy();
}
var $next = $(this).find(_options.nextSelector).first();
data.waiting = false;
data.nextHref = $next.attr('href') ? $.trim($next.attr('href') + ' ' + _options.contentSelector) : false;
$('.jscroll-next-parent', $e).remove(); // Remove the previous next link now that we have a new one
_checkNextHref();
if (_options.callback) {
_options.callback.call(this);
}
_debug('dir', data);
});
});
},
// Safe console debug - http://klauzinski.com/javascript/safe-firebug-console-in-javascript
_debug = function(m) {
if (_options.debug && typeof console === 'object' && (typeof m === 'object' || typeof console[m] === 'function')) {
if (typeof m === 'object') {
var args = [];
for (var sMethod in m) {
if (typeof console[sMethod] === 'function') {
args = (m[sMethod].length) ? m[sMethod] : [m[sMethod]];
console[sMethod].apply(console, args);
} else {
console.log.apply(console, args);
}
}
} else {
console[m].apply(console, Array.prototype.slice.call(arguments, 1));
}
}
};
// Initialization
$e.data('jscroll', $.extend({}, _data, {initialized: true, waiting: false, nextHref: _nextHref}));
_wrapInnerContent();
_preloadImage();
_setBindings();
// Expose API methods via the jQuery.jscroll namespace, e.g. $('sel').jscroll.method()
$.extend($e.jscroll, {
destroy: _destroy
});
return $e;
};
// Define the jscroll plugin method and loop
$.fn.jscroll = function(m) {
return this.each(function() {
var $this = $(this),
data = $this.data('jscroll'), jscroll;
// Instantiate jScroll on this element if it hasn't been already
if (data && data.initialized) {
return;
}
jscroll = new jScroll($this, m);
});
};
})(jQuery);
Can anyone point me in the direction of what is wrong here - is it the placement of the scripts ?
In the filter ajax call, I do call the footer again so the jScroll script is part of the load in the filter function called.
I am using Laravel 4.1 and created a global filter which redirects to a particular page if any of the following value is null.
Name
email
DOB
Religion
Caste
In the above values Caste is populated dynamically. When the religion value is changed. Everything was working fine With the below code in filter.php:
if (is_null(value->name)) {
return Redirect::to('confirm');
}
if (is_null(value->email)) {
return Redirect::to('confirm');
}
if (is_null($value->dob) {
return Redirect::to('confirm');
}
But when I added Religion or caste or both. The jQuery in the page crashes that is the dropdown isn't populating properly and the entire browser hangs.
if (is_null(value->name)) {
return Redirect::to('confirm');
}
if (is_null(value->email)) {
return Redirect::to('confirm');
}
if (is_null($value->dob) {
return Redirect::to('confirm');
}
if (is_null($value->religion) {
return Redirect::to('confirm');
}
if (is_null($value->caste) {
return Redirect::to('confirm');
}
I don't why it is happening; the first three work completely fine.
jQuery:
var Religion = '#Religion' ;
var Caste = '#Caste' ;
var caste = new Array();
var usr ;
$(function () {
$.ajaxSetup({
async: false
});
usr = getUser();
if(!$.isEmptyObject(usr))
{
var data = getCasteForReligion(usr.religionid) ;
if (data != null) {
// alert(data);
caste = new Array();
for (var i = 0; i < data.length; i++) {
caste.push(data[i]);
}
loadCastes(caste);
}
if(user.casteid != null)
{
$(Caste).val(usr.casteid).trigger('list:updated');
}
}
$(Religion).change(function () {
if ($(Religion).val() != "") {
var data = getCasteForReligion($(Religion).val());
if (data != null) {
// alert(data);
caste = new Array();
for (var i = 0; i < data.length; i++) {
caste.push(data[i]);
}
loadCastes(caste);
}
}
else {
}
});
});
function getCasteForReligion(religionid) {
var result;
$.get('/getCastes',
{ religionId : religionid },
function(data) {
result = data;
});
return result;
}
function getUser() {
var result;
$.get( '/User',
{ },
function(data) {
result = data;
});
return result;
}
//Generate Products variant for Indent
function loadCastes(castlst) {
$(Caste).find('option').remove();
$(Caste).val('').trigger('list:updated');
$(Caste).append(new Option("--Select--", "")).trigger('list:updated');
for (var i = 0; i < castlst.length; i++) {
$(Caste).append(new Option(castlst[i].name, castlst[i].id)).trigger('list:updated');
}
}
I have a ajax live search script working with php to search a database automatically when you type.
However I am now trying to use GET function to place a value into the search box from the url. Everything is working fine and the value is placed in to input box however it wont search unless you type.
How do i get it to search when the page loads with the value from the url?
Here is the ajax script:
var ls = {
url: "ajax/process_livesearch.php",
form_id: "#ls_form",
form_anti_bot_id: "#ls_anti_bot",
form_anti_bot: "Ehsan's guard",
query_id: "#ls_query",
result_id: "#ls_result_div",
footer_id: "#ls_result_footer",
current_page_hidden_id: "#ls_current_page",
current_page_lbl_id: "#ls_current_page_lbl",
last_page_lbl_id: "#ls_last_page_lbl",
page_range_id: "#ls_items_per_page",
navigation_class: ".navigation",
arrow_class: ".arrow",
next_page_id: "ls_next_page",
previous_page_id: "ls_previous_page",
slide_speed: "fast",
type_delay: 350,
select_column_index: 1
};
var result = $(ls.result_id);
var query = $(ls.query_id);
var footer = $(ls.footer_id);
var current_page = $(ls.current_page_hidden_id);
var current_page_lbl = $(ls.current_page_lbl_id);
var total_page_lbl = $(ls.last_page_lbl_id);
var page_range = $(ls.page_range_id);
var select_result;
function show_result() {
result.slideDown(ls.slide_speed)
}
function hide_result() {
result.slideUp(ls.slide_speed)
}
function remove_select_options(a) {
var b, c;
b = page_range.data("selected_option", page_range.val()).find("option");
if (page_range.data("all_options") === undefined) {
page_range.data("all_options", b)
} else {
page_range.empty();
page_range.append(page_range.data("all_options"))
}
c = false;
$(page_range.data("all_options")).each(function () {
if (this.value >= a) {
if (this.value === page_range.data("selected_option")) {
c = true
}
$(this).remove()
}
});
if (c) {
page_range.val("0")
} else {
page_range.val(page_range.data("selected_option"))
}
if (page_range.find("option").length <= 1) {
footer.hide();
result.find("table").addClass("border_radius")
} else {
result.find("table").removeClass("border_radius");
footer.show()
}
}
function remove_footer() {
result.off("click", "tr", select_result);
footer.hide();
result.find("table").addClass("border_radius")
}
function search_query(c, b, a) {
if ($.trim(c.value).length) {
if (b || c.latest_value !== c.value) {
if (a) {
current_page.val("1");
current_page_lbl.html("1")
}
c.selected_row = undefined;
if (c.to_be_executed) {
clearTimeout(c.to_be_executed)
}
c.to_be_executed = setTimeout(function () {
if ($.trim(query.val()).length) {
query.addClass("ajax_loader");
$.ajax({
type: "post",
url: ls.url,
data: $(ls.form_id).serialize(),
dataType: "json",
success: function (d) {
if (d.status === "success") {
var e = $.parseJSON(d.result);
result.find("table tbody").html(e.html);
if (e.number_of_results === 0) {
remove_footer()
} else {
if (e.total_pages > 1) {
$(ls.navigation_class).show();
total_page_lbl.html(e.total_pages)
} else {
$(ls.navigation_class).hide()
}
remove_select_options(e.number_of_results);
result.on("click", "tr", select_result)
}
} else {
result.find("table tbody").html(d.message);
remove_footer()
}
},
error: function () {
result.find("table tbody").html("Something went wront. Please refresh the page.");
remove_footer()
},
complete: function () {
if ($.trim(c.value).length && result.is(":hidden")) {
show_result()
}
query.removeClass("ajax_loader")
}
})
}
}, ls.type_delay)
}
} else {
if (result.is(":visible") || result.is(":animated")) {
hide_result()
}
}
c.latest_value = c.value
}
select_result = function () {
query.val($(query.selected_row).find("td").eq(ls.select_column_index).html());
hide_result()
};
function adjust_result_position() {
$(result).css({left: query.position().left + 1, width: query.outerWidth() - 2})
}
$(document).ready(function () {
adjust_result_position();
$(window).resize(function () {
adjust_result_position()
});
$(ls.form_anti_bot_id).val(ls.form_anti_bot);
$(query).on("keyup", function (c) {
var b = c.keyCode || c.which;
if ($.trim(query.val()).length && b === 13) {
if ((result.is(":visible") || result.is(":animated")) && result.find("tr").length !== 0) {
if (query.selected_row !== undefined) {
$(result).find("tr").trigger("click")
}
} else {
show_result()
}
} else {
search_query(this, false, true)
}
});
$(query).on("keydown", function (c) {
var b = c.keyCode || c.which;
if (b === 40 || b === 38) {
if ($.trim(query.val()).length && result.find("tr").length !== 0) {
if ((result.is(":visible") || result.is(":animated"))) {
result.find("tr").removeClass("hover");
if (query.selected_row === undefined) {
query.selected_row = result.find("tr").eq(0);
$(query.selected_row).addClass("hover")
} else {
$(query.selected_row).removeClass("hover");
if (b === 40) {
if ($(query.selected_row).next().length === 0) {
query.selected_row = result.find("tr").eq(0);
$(query.selected_row).addClass("hover")
} else {
$(query.selected_row).next().addClass("hover");
query.selected_row = $(query.selected_row).next()
}
} else {
if ($(query.selected_row).prev().length === 0) {
query.selected_row = result.find("tr").last();
query.selected_row.addClass("hover")
} else {
$(query.selected_row).prev().addClass("hover");
query.selected_row = $(query.selected_row).prev()
}
}
}
} else {
if (b === 40) {
show_result()
}
}
}
}
});
$(query).on("focus", function () {
if ($.trim(query.val()).length && (result.is(":hidden") || result.is(":animated")) && result.find("tr").length !== 0) {
search_query(this, false, true);
show_result()
}
});
$(result).on("mouseover", "tr", function () {
result.find("tr").removeClass("hover");
query.selected_row = this;
$(this).addClass("hover")
});
$(result).on("mouseleave", "tr", function () {
result.find("tr").removeClass("hover");
query.selected_row = undefined
});
$(result).on("click", "tr", select_result);
var a;
$(document).bind("touchstart", function () {
a = $(window).scrollTop()
}).bind("touchend", function (c) {
var d, b;
d = a - $(window).scrollTop();
b = $(document);
b.addClass("touched");
if (d < 10 && d > -10) {
if (!$(c.target).closest(result).length && !$(c.target).is(query) && $(result).is(":visible")) {
hide_result()
}
}
});
$(document).on("click", function (b) {
if ($(this).hasClass("touched")) {
$(this).removeClass("touched")
} else {
if (!$(b.target).closest(result).length && !$(b.target).is(query) && $(result).is(":visible")) {
hide_result()
}
}
});
$(ls.form_id).submit(function () {
return false
});
$(ls.arrow_class).on("click", function () {
var b;
if (this.id === ls.next_page_id) {
if (parseInt(current_page.val(), 10) + 1 <= parseInt(total_page_lbl.html(), 10)) {
b = parseInt(current_page.val(), 10) + 1
} else {
return
}
} else {
if (parseInt(current_page.val(), 10) - 1 >= 1) {
b = parseInt(current_page.val(), 10) - 1
} else {
return
}
}
current_page.val(b);
current_page_lbl.html(b);
search_query(query[0], true, false)
});
$(page_range).on("change", function () {
search_query(query[0], true, true)
})
});
Any input on this matter will be much appreciated and a solution would be heaven.
Thanks in advance
I found a easy way by just including this little script on the bottom of my page
<script type="text/javascript">
window.onload=function() {
var text_input = document.getElementById ('ID_of_element');
text_input.focus ();
text_input.select ();
}
</script>
This highlights the text and searches.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I am trying to make an app where users can crop the image then save then can download it, but after cropping when i click on save button the png image created is of 0kb...
what could be the error?
this is my js file
function getIndex(e) {
var t = c.getObjects();
for (var n in t) {
if (t[n] == e) {
return n
}
}
}
function loadingShow(e) {
$("#overlay_loading").show();
$("#overlay_loading #load_message").html(e);
$("body").css("overflow", "hidden")
}
function loadingHide() {
$("#overlay_loading").hide();
$("body").css("overflow", "inherit")
}
function getData() {
var e = $("body").data("dats")
}
function reloadThumbs(e) {
if (!cropping) {
var t = $($("#object_layers li").get().reverse());
if (e) {
var n = [];
var r = getIndex(e);
n[r] = e
} else {
var n = c.getObjects();
var i = "";
if (n.length !== t.length) {
$("#object_layers").empty();
for (var s = 0; s < n.length; s++) {
var o = $('<image width="120" height="75" />').attr("src", i);
$("<li/>").prependTo("#object_layers").append(o)
}
t = $($("#object_layers li").get().reverse())
}
}
for (s in n) {
if (n[s] !== undefined) {
var u = fabric.document.createElement("canvas");
if (!u.getContext && typeof G_vmlCanvasManager != "undefined") {
G_vmlCanvasManager.initElement(u)
}
u.width = $("#cc").width();
u.height = $("#cc").height();
fabric.util.wrapElement(u, "div");
var a = new fabric.Canvas(u);
a.backgroundColor = "transparent";
var f = n[s].isActive();
a.add(n[s]);
a.renderAll();
var i = a.toDataURLWithMultiplier("png", .35101058);
if (f) {}
$(t.get(s)).find("img").attr("src", i);
$("#object_layers li").click(function () {
$("#object_layers li").removeClass("layer_selected");
$(this).addClass("layer_selected")
})
}
}
reloadData()
}
}
function reloadLayers() {
$($("#object_layers li").get().reverse()).each(function () {
if ($(this).data("object") !== undefined) c.bringToFront($(this).data("object"))
});
reloadData()
}
function reloadData() {
var e = c.getObjects();
var t = $($("#object_layers li").get().reverse());
for (var n in e) {
if (e[n] !== undefined) {
$(t.get(n)).data("object", e[n])
}
}
c.selection = false
}
function cropStart() {
cropping = true;
c.forEachObject(function (e) {
e.selectable = false
});
var e = actObj;
var t = {
left: 450,
top: 150,
width: 300,
height: 200
};
console.log(t);
cropObject = new Crop({
left: t.left,
top: t.top,
fill: "rgba(255,255,255,0)",
width: t.width,
height: t.height
});
c.add(cropObject);
c.deactivateAll();
cropObject.selectable = true;
c.setActiveObject(cropObject);
c.bringToFront(cropObject);
c.renderAll();
$("#crop_control").show()
}
function crop() {
var e = cropObject.width * cropObject.scaleX;
var t = cropObject.height * cropObject.scaleY;
var n = cropObject.left - e / 2;
var r = cropObject.top - t / 2;
var i = actObj;
i.clone(function (s) {
var o = fabric.document.createElement("canvas");
if (!o.getContext && typeof G_vmlCanvasManager != "undefined") {
G_vmlCanvasManager.initElement(o)
}
o.width = e;
o.height = t;
fabric.util.wrapElement(o, "div");
var u = new fabric.Canvas(o);
u.backgroundColor = "transparent";
s.setOpacity(1);
u.add(s);
s.left -= n;
s.top -= r;
u.renderAll();
var a = u.toDataURL();
var f = $("<img src=" + a + " />").get(0);
i.scaleX = 1;
i.scaleY = 1;
i.setElement(f);
i.width = e;
i.height = t;
i.setAngle(0);
c.setActiveObject(i);
c.renderAll();
setTimeout(function () {
c.renderAll();
reloadThumbs(i)
}, 100);
reloadThumbs()
});
cropFinish()
}
function cropFinish() {
$("#crop_control").hide();
$(".ct").removeAttr("disabled");
$("#object_layers").sortable("enable");
cropping = false;
c.remove(cropObject);
cropObject = null
}
var cropping = false;
var c = new fabric.Canvas("cc");
var start, set = "personal";
c.setOverlayImage("img/foreground-personal.png", c.renderAll.bind(c));
c.backgroundColor = "rgba(59,89,152,1)";
$(function () {
if (window.File && window.FileReader && window.FileList && window.Blob) {} else {}
$("#fileupload").fileupload({
add: function (e, t) {
if (typeof FileReader !== "undefined") {
$(t.files).each(function (e) {
var t = this;
var n = new FileReader;
n.onload = function (e) {
var t = e.target.result;
fabric.Image.fromURL(t, function (e) {
if (e.getWidth() > 800) {
e.scaleToWidth(800)
}
if (e.getHeight() > 400) {
e.scaleToHeight(400)
}
c.add(e);
e.setActive(true);
c.centerObjectH(e).centerObjectV(e);
e.setCoords();
c.renderAll();
var n = $('<image width="120" height="55" />').attr("src", t);
$("<li/>").prependTo("#object_layers").append(n);
reloadThumbs()
})
};
n.readAsDataURL(t)
})
} else {
t.submit()
}
},
dataType: "json",
done: function (e, t) {
$.each(t.result, function (e, t) {
$("<p/>").text(t.name).appendTo(document.body);
fabric.Image.fromURL(t.url, function (e) {
var t = e.set({
left: 110,
top: 75
}).scale(.7);
c.add(t).renderAll()
})
})
}
});
$(document).keydown(function (e) {
if (e.which == 46 && !cropping) {
var t = c.getActiveObject();
if (t) {
c.remove(t);
reloadThumbs()
}
}
});
$("#save").click(function () {
var e = JSON.stringify(c);
loadingShow("Saving... Please Wait...");
$.ajax({
type: "POST",
url: "ajax.php",
data: {
d: e
}
}).done(function (e) {
loadingHide();
alert("Data Saved!")
})
})
});
c.observe("object:modified", function (e) {
reloadThumbs(e.target)
});
c.observe("object:selected", function (e) {
var t = e.target;
var n = getIndex(t);
if (t.type == "image") {
$(".ot").attr("disabled", "disabled").val("");
$(".oi").removeAttr("disabled")
} else if (t.type == "text") {
$(".oi").attr("disabled", "disabled");
$(".ot").removeAttr("disabled");
var r = t.toObject();
var i = t.getFill();
if (start && r.text == "Click here to start") {
c.clear();
reloadThumbs();
start = false
}
$("#text_text").val(r.text);
$("#text_color").val(i.toUpperCase());
$("#text_font").val(r.fontFamily)
}
});
c.observe("selection:cleared", function (e) {
$(".ot").val("").attr("disabled", "disabled");
$(".oi").val("").attr("disabled", "disabled")
});
var cropObject = null;
var actObj;
$("#image_crop").click(function () {
$(this).attr("disabled", "disabled");
$(".ct").attr("disabled", "disabled");
$("#object_layers").sortable("disable");
actObj = c.getActiveObject();
cropStart();
return false
});
$("#crop_ok").click(function () {
crop();
c.forEachObject(function (e) {
e.selectable = true
})
});
$("#crop_cancel").click(function () {
cropping = false;
cropFinish();
c.setActiveObject(actObj);
c.forEachObject(function (e) {
e.selectable = true
});
return false
})
this is the save code in js using ajax
$("#save").click(function () {
var e = JSON.stringify(c);
loadingShow("Saving... Please Wait...");
$.ajax({
type: "POST",
url: "ajax.php",
data: {
d: e
}
}).done(function (e) {
loadingHide();
alert("Data Saved!")
})
})
});
this my php file
echo $_POST['e'];
echo json_decode($_POST['e']);
echo var_dump(json_decode($_POST['e']));
$name=time();
file_put_contents("uploads/" . $name . ".png", $data);
Your posted data has a key d but you are trying to read from e which doesn't have a value.
Even if that wasn't the case, then I'm pretty sure that no valid JSON data will decode to be a PNG binary anyway.