using multiple waypoints in google directions service - php

I have following code for the functionality in my site to calculate distance between a pickup address, a drop-off address and one waypoint (optional).
if ( Google_AutoComplete_Country != 'ALL_COUNTRIES' ) {
var options = {
componentRestrictions: {country: Google_AutoComplete_Country}
};
} else {
var options = '';
}
//if(form_tab == 'distance') {
/** Added by PG. */
//Condition to show return fields when return-journey is set to Return
$('#return-journey').change(function(){
if( $(this).val() === 'true' ) {
//Show return block
$('.return-block').css('display', 'block');
returnAdd = false;
returnVia = false;
//Return Address Autocomplete
var returnAdd_input = document.getElementById('return-address');
var returnAdd_autocomplete = new google.maps.places.Autocomplete(returnAdd_input,options);
google.maps.event.addListener(returnAdd_autocomplete, 'place_changed', function() {
var returnAdd_place = returnAdd_autocomplete.getPlace();
if (typeof returnAdd_place.adr_address === 'undefined') {
returnAdd = false;
} else {
returnAdd = true;
}
});
//Return Via Autocomplete
var returnVia_input = document.getElementById('return-via');
var returnVia_autocomplete = new google.maps.places.Autocomplete(returnVia_input,options);
google.maps.event.addListener(returnVia_autocomplete, 'place_changed', function() {
var returnVia_place = returnVia_autocomplete.getPlace();
if (typeof returnVia_place.adr_address === 'undefined') {
returnVia = false;
} else {
returnVia = true;
}
});
//Return Dropoff Autocomplete
var returnDropoff_input = document.getElementById('return-dropoff');
var returnDropoff_autocomplete = new google.maps.places.Autocomplete(returnDropoff_input, options);
google.maps.event.addListener(returnDropoff_autocomplete, 'place_changed', function() {
var returnDropoff_place = returnDropoff_autocomplete.getPlace();
if(typeof returnDropoff_place.adr_address === 'undefined'){
returnDropoff = false;
} else {
returnDropoff = true;
}
});
if(document.getElementById('atbReturnMap') !== null) {
var map = new google.maps.Map(document.getElementById('atbReturnMap'), {
mapTypeControl: false,
streetViewControl: false,
center: {lat: 53.0219186, lng: -2.2297829},
zoom: 8
});
var return_pickup_address_input = document.getElementById('return-address');
var return_dropoff_address_input = document.getElementById('return-dropoff');
var return_pickup_via_input = document.getElementById('return-via');
var return_route_distance_label = document.getElementById('display-return-route-distance');
var return_route_distance_string_input = document.getElementById('return-route-distance-string');
var return_route_distance_input = document.getElementById('return-route-distance');
var return_route_time_label = document.getElementById('display-return-route-time');
var return_route_time_input = document.getElementById('return-route-time');
new AutocompleteDirectionsHandler(map, return_pickup_address_input, return_dropoff_address_input, return_pickup_via_input, return_route_distance_label, return_route_distance_input, return_route_distance_string_input, return_route_time_label, return_route_time_input);
}
}
else {
$('.return-block').css('display', 'none');
returnAdd = undefined;
returnVia = undefined;
returnDropoff = undefined;
}
});
/** END - Added by PG. */
if(document.getElementById('atbMap') !== null) {
var map = new google.maps.Map(document.getElementById('atbMap'), {
mapTypeControl: false,
streetViewControl: false,
center: {lat: 53.0219186, lng: -2.2297829},
zoom: 8
});
console.log(document.getElementById('pickup-address1'));
var pickup_address_input = document.getElementById('pickup-address1');
var dropoff_address_input = document.getElementById('dropoff-address1');
var pickup_via_input = document.getElementById('pickup-via1');
var waypointsInput = newInput;
var first_route_distance_label = document.getElementById('display-route-distance');
var first_route_distance_string_input = document.getElementById('route-distance-string');
var first_route_distance_input = document.getElementById('route-distance');
var first_route_time_label = document.getElementById('display-route-time');
var first_route_time_input = document.getElementById('route-time');
new AutocompleteDirectionsHandler( map, pickup_address_input, dropoff_address_input, pickup_via_input, first_route_distance_label, first_route_distance_input, first_route_distance_string_input, first_route_time_label, first_route_time_input, waypointsInput);
}
//}
/** Start */
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map, originInput, destinationInput, waypointInput, routeDisplayElement, routeInputElement, routeInputStringElement, timeDisplayElement, timeInputElement,waypointsInput) {
this.map = map;
this.routeDisplayElement = routeDisplayElement;
this.routeInputElement = routeInputElement;
this.routeInputStringElement = routeInputStringElement;
this.timeDisplayElement = timeDisplayElement;
this.timeInputElement = timeInputElement;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.waypointPlaceId = [];
this.travelMode = 'DRIVING';
var originInput = originInput;
var destinationInput = destinationInput;
var waypointInput = waypointInput;
var waypointsInput = waypointsInput;
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
this.directionsDisplay.setMap(map);
var originAutocomplete = new google.maps.places.Autocomplete(
originInput, options);
var destinationAutocomplete = new google.maps.places.Autocomplete(
destinationInput, options);
var waypointAutocomplete = new google.maps.places.Autocomplete(
waypointInput, options);
// waypointAutocomplete = [];
this.setupPlaceChangedListener = function(autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
function checkPlaceAddress(adr){
if ( typeof adr === 'undefined') {
window.alert("Please select an option from the dropdown list.");
return false;
} else {
return true;
}
}
switch(mode){
case 'ORIG':
pickup_1 = checkPlaceAddress(place.adr_address);
if(pickup_1) me.originPlaceId = place.place_id;
$('#pickup-address-lat').val(place.geometry.location.lat());
$('#pickup-address-lng').val(place.geometry.location.lng());
break;
case 'DEST':
dropoff_1 = checkPlaceAddress(place.adr_address);
if(dropoff_1) me.destinationPlaceId = place.place_id;
$('#dropoff-address-lat').val(place.geometry.location.lat());
$('#dropoff-address-lng').val(place.geometry.location.lng());
break;
case 'WAYPT':
pickupVia = checkPlaceAddress(place.adr_address);
if(pickupVia) me.waypointPlaceId = { location: place.formatted_address, stopover: true };
$('#pickup-via-lat').val(place.geometry.location.lat());
$('#pickup-via-lng').val(place.geometry.location.lng());
break;
}
me.route();
});
};
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
this.setupPlaceChangedListener(waypointAutocomplete, 'WAYPT');
//this.setupPlaceChangedListener(WptPlace[0], 'WAYPT');
}
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
var directions = {
origin: {'placeId': me.originPlaceId},
destination: {'placeId': me.destinationPlaceId},
travelMode: me.travelMode
};
if(me.waypointPlaceId != undefined) {
directions.waypoints = [me.waypointPlaceId]
}
me.directionsService.route(directions, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
//console.log(me.directionsDisplay.getDirections());
computeTotalDistance(me.directionsDisplay.getDirections(), me.routeDisplayElement, me.routeInputElement, me.routeInputStringElement, me.timeDisplayElement, me.timeInputElement);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
the relevant HTML code is as follows:
<form class="booking-form-1 one-way-transfer-form">
<input type="text" name="pickup-address" id="pickup-address1" class="pickup-address" placeholder="' . esc_html__( 'Pick Up Address', 'chauffeur' ) . '" />
<div class="pickup-via-input">
<div class="via_wrapper" id="via_wrapper">
<div>
<input type="text" id="pickup-via1" class="pickup-via" placeholder="' . esc_html__( 'Pickup Via Address', 'chauffeur' ) . '" />
<img src="'. get_stylesheet_directory_uri() .'/images/add-icon.png"/>
</div>
</div>
</div>
<input type="text" name="dropoff-address" id="dropoff-address1" class="dropoff-address" placeholder="' . esc_html__( 'Drop Off Address', 'chauffeur' ) . '" />
<input type="checkbox" id="waypoint-check" class="waypoint-check" /> <span style="color:#fff">Add Waypoint</span>
<div class="clear"></div>
<div class="route-content">
<div id="display-route-distance" class="left-col-distance"></div>
<div id="display-route-time" class="right-col-time"></div>
</div>
<div class="clear"></div>
<input type="hidden" name="route-distance-string" id="route-distance-string" />
<input type="hidden" name="route-distance" id="route-distance" />
<input type="hidden" name="route-time" id="route-time" />
<div id="atbMap"></div>
<input type="hidden" name="pickup-address-lat" id="pickup-address-lat" />
<input type="hidden" name="pickup-address-lng" id="pickup-address-lng" />
<input type="hidden" name="pickup-via-lat" id="pickup-via-lat" />
<input type="hidden" name="pickup-via-lng" id="pickup-via-lng" />
<input type="hidden" name="dropoff-address-lat" id="dropoff-address-lat" />
<input type="hidden" name="dropoff-address-lng" id="dropoff-address-lng" />
Now I want to add the feature of adding multiple waypoint inputs using +, - button.
how do I set up the place changed listener everytime the new waypoint is added, so that it calculates all the previous waypoints also if any.
Here is the coded that I've added for multiple waypoints and adding autocomplete in it.
$('.add_button').click(function(){
pickupViaCount++;
//console.log(pickupViaCount);
var fieldHTML = '<div><input type="text" id="pickup-via'+ pickupViaCount +'" class="pickup-via" placeholder="Pickup Via Address" /><img src="' + path_vars.image_dir_path + '/remove-icon.png"/></div>';
$('.via_wrapper').append(fieldHTML);
var newEl = document.getElementById('pickup-via' + pickupViaCount);
var placee2 = new google.maps.places.Autocomplete(newEl, options);
newInput.push(newEl);

Related

Joomla Interesting search module error!(SJ Filter for VirtueMart )

I would like to ask for help with the following topic!
We use SJ Filter for VirtueMart on our website! However the price filter uses price without tax. It's not good this way.I think the system uses the "base price" (without tax).I would like the filter use "end user price" with tax.(27.tax).I didn't find anything in the setting. I attached files from filter.I checked the code but I couldn't find anything that I could change.
Please someone help !
enter image description here
enter image description here
<?php
/**
* #package SJ Filter for VirtueMart
* #version 2.0.0
* #license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
* #copyright (c) 2014 YouTech Company. All Rights Reserved.
* #author YouTech Company http://www.smartaddons.com
*/
defined ('_JEXEC') or die;
?>
<script type="text/javascript">
//<![CDATA[
jQuery(document).ready(function ($) {
;
(function (element) {
var $element = $(element),
$_ft_form = $('.ft-form', $element),
$_group_ft = $('.ft-group', $element),
$_filtering = $('.ft-filtering', $element)
$_ajax_url = '<?php echo (string)JURI::getInstance(); ?>';
var $_gr_prices = $('.ft-group-prices', $element),
$_slide_prices = $(".ft-slider-price", $_gr_prices),
_min_price = <?php echo (int)$params->get('price_min',0); ?>,
_max_price = <?php echo (int)$params->get('price_max',1300000); ?>;
var $timer = 0;
$_slide_prices.each(function (index, element) {
$(this)[index].slide = null;
});
$_slide_prices.slider({
range: true,
min: _min_price,
max: _max_price,
values: [_min_price, _max_price],
slide: function (event, ui) {
$(".ft-price-min", $_gr_prices).val(ui.values[0]);
$(".ft-price-max", $_gr_prices).val(ui.values[1]);
if ($timer) {
clearTimeout($timer);
}
$timer = setTimeout(
function () {
processAjax()
}, 1000);
}
});
$('.ft-price-input', $_gr_prices).on('keyup', function () {
var $that = $(this);
if ($timer) {
clearTimeout($timer);
}
var _price_tmp = parseInt($that.val());
$timer = setTimeout(function () {
if (!isNaN(_price_tmp) && _price_tmp >= 1) {
_price_tmp = _price_tmp >= _max_price ? _max_price : _price_tmp;
if ($that.hasClass('ft-price-min')) {
var _maxp = $(".ft-price-max", $_gr_prices).val();
_maxp = (_maxp != '' ) ? _maxp : _max_price;
_price_tmp = _price_tmp >= _maxp ? _maxp : _price_tmp;
$that.val(_price_tmp);
$_slide_prices.slider("values", 0, _price_tmp);
} else {
var _minp = $(".ft-price-min", $_gr_prices).val();
_minp = (_minp != '' ) ? _minp : _min_price;
_price_tmp = (_price_tmp >= _minp && _price_tmp <= _max_price ) ? _price_tmp : _minp;
$that.val(_price_tmp);
$_slide_prices.slider("values", 1, _price_tmp);
}
} else {
if ($that.hasClass('ft-price-min')) {
$that.val('');
$_slide_prices.slider("values", 0, _min_price);
} else {
$that.val('');
$_slide_prices.slider("values", 1, _max_price);
}
}
processAjax();
}, 1000);
});
// var $_open_close = $('.ft-open-close ', $_group_ft);
// $_open_close.on('click ', function () {
// var $_parent = $(this).parents('.ft-heading');
// $_parent.siblings('.ft-content').stop(true, false).slideToggle(400, function () {
// if ($_parent.parent().hasClass('ft-open')) {
// $_parent.parent().removeClass('ft-open').addClass('ft-close');
// }
// else {
// $_parent.parent().removeClass('ft-close').addClass('ft-open');
// }
// });
//
// });
var $_ft_heading = $('.ft-heading', $_group_ft);
$_ft_heading.on('click', function () {
$(this).siblings('.ft-content').stop(true, false).slideToggle(400, function () {
if ($(this).parent().hasClass('ft-open')) {
$(this).parent().removeClass('ft-open').addClass('ft-close');
} else {
$(this).parent().removeClass('ft-close').addClass('ft-open');
}
});
});
if ($('.ft-group', $element).width() <= 200) {
$('.sj-vm-filter .ft-content-prices .ft-price-value input[type="text"]').css('width', '38px');
}
//.ft-opt-count
var $_label_opt = $('.ft-opt-name, .ft-color-value', $_group_ft);
$_label_opt.on('click ', function () {
var _input_check = $(this).siblings('input[type="checkbox"]'),
_checked = _input_check.prop('checked'),
_color_value = $(this).is('.ft-color-value');
if (_checked) {
if (_color_value) {
$(this).removeClass('ft-checked');
}
_input_check.removeAttr('checked');
} else {
if (_color_value) {
$(this).addClass('ft-checked');
}
_input_check.attr('checked', 'checked');
}
processAjax();
});
function showClearAll() {
var $ft_content = $('.ft-content', $_group_ft);
$ft_content.each(function () {
var $that = $(this);
var $i = 0;
$(':input', $that).each(function () {
if ($(this).prop('checked')) {
$i++;
}
});
if ($i > 0) {
$('.ft-opt-clearall', $that).fadeIn(500);
} else {
$('.ft-opt-clearall', $that).fadeOut(500);
}
});
}
$('input[type="hidden"]', $element).val('');
$('input[type="hidden"]', $_group_ft).val('');
$(':checkbox ', $_group_ft).removeAttr('checked');
$(':checkbox ', $_group_ft).on('click', function () {
processAjax();
});
$('.ft-opt-clearall', $_group_ft).unbind('click.clearall').on('click.clearall', function () {
var _ft_select = $(this).siblings('.ft-select');
$('input[type="checkbox"]', _ft_select).removeAttr('checked');
$('.ft-color-value', _ft_select).removeClass('ft-checked');
processAjax();
});
var _config_global = '';
function processAjax() {
var fields = $(":input", $element).serialize();
_config_global = fields;
showClearAll();
var _loading = $('<div class="sj-loading" ><div class="ft-image-loading"></div></div>');
$("body").append(_loading);
$.ajax({
type: 'POST',
url: $_ajax_url,
data: {
is_ajax_ft: 1,
ft_module_id: <?php echo $module->id ?>,
_config_data: _config_global
},
success: function (data) {
_loading.remove();
if (data.items_markup != '') {
$('.ft-filtering', $_ft_form).replaceWith(data.items_markup);
updateAfterLoadAjax();
}
if (data.filter_product != '') {
if ($('<?php echo $params->get('area_results'); ?>').length) {
$('<?php echo $params->get('area_results'); ?>').html(data.filter_product);
updateAfterLoadAjax();
}
}
if (data == 'noresults') {
window.location.href = $_ajax_url;
}
},
error: function () {
_loading.remove();
},
dataType: 'json'
});
}
var parseQueryString = function (queryString) {
var params = {}, queries, temp, i, l;
queries = queryString.split("&");
for (i = 0, l = queries.length; i < l; i++) {
temp = queries[i].split('=');
params[temp[0]] = temp[1];
}
return params;
};
function updateAfterLoadAjax() {
if(typeof Virtuemart !== 'undefined'){
var $_form = $("form.product");
Virtuemart.product($_form);
}
var $_ft_result = $('#ft_results_<?php echo $module->id; ?>');
$('.orderlistcontainer', $_ft_result).hover(
function () {
$(this).find('.orderlist').stop().show()
},
function () {
$(this).find('.orderlist').stop().hide()
}
)
var $_orderList = $('.orderlist', $_ft_result);
if ($_orderList.length > 0) {
$_orderList.children().on('click', function () {
var _href = $('a ', $(this)).attr('href');
_href = _href.replace(/\?/g, '&').replace('by,', 'orderby=');
_href = _href.replace(/\//g, '&');
var _orderby = parseQueryString(_href);
$('.config-orderby', $element).attr('value', _orderby.orderby);
processAjax();
return false;
});
}
var $_selectbox = $('select.inputbox', $_ft_result);
var _limit = $('option:selected', $_selectbox).text();
$('option:selected', $_selectbox).each(function(){
var _limit = $(this).text();
$('.config-limit', $element).attr('value', _limit);
$_selectbox.removeAttr('onchange');
$_selectbox.on('change', function () {
var _value = $('option:selected', $(this)).text();
$('.config-limit', $element).attr('value', _value);
processAjax();
return false;
});
});
//add product_load_limit last run processAjax() in select box
var pro_load = "<?php echo $params->get('limit_results',5)?>";
var url_option = "<?php echo JURI::base(true).'/?limit=';?>";
var _option = '<option value="' + url_option + pro_load + '">' + pro_load + '</option>';
var $_selectbox_2 = $('select.inputbox option:first', $_ft_result);
if ($_selectbox_2.text() != pro_load) {
$_selectbox_2.before(_option);
}
var $vm_pagination = $('.vm-pagination ul', $_ft_result);
if ($vm_pagination.length > 0) {
$vm_pagination.children().on('click', function () {
var $this = $(this);
if ($this.is('.disabled') || $this.is('.active')) {
return false;
} else {
var _href = $('a ', $(this)).attr('href');
_href = _href.replace(/\?/g, '&').replace('results,', 'limit_start=');
_href = _href.replace(/\//g, '&');
var _lmstart = parseQueryString(_href);
var _start = 0;
if (typeof _lmstart.limit_start != 'undefined') {
_start = _lmstart.limit_start
_start = _start.split("-");
_start = _start[1];
} else if (typeof _lmstart.start != 'undefined') {
_start = _lmstart.start;
}
$('.config-limitstart', $element).attr('value', _start);
processAjax();
}
return false;
});
}
// Click Button
function display(view) {
jQuery('.browse-view .row').removeClass('vm-list vm-grid').addClass(view);
jQuery('.icon-list-grid .vm-view').removeClass('active');
if(view == 'vm-list') {
jQuery('.browse-view .product').addClass('col-lg-12 product-full');
jQuery('.browse-view .product .product-left').addClass('col-md-4');
jQuery('.browse-view .product .product-right').addClass('col-md-8');
jQuery('.icon-list-grid .' + view).addClass('active');
}else{
jQuery('.browse-view .product').removeClass('col-lg-12 product-full');
jQuery('.browse-view .product .product-left').removeClass('col-md-4');
jQuery('.browse-view .product .product-right').removeClass('col-md-8');
jQuery('.icon-list-grid .' + view).addClass('active');
}
}
jQuery('.vm-view-list .vm-view').each(function() {
var ua = navigator.userAgent,
event = (ua.match(/iPad/i)) ? 'touchstart' : 'click';
jQuery('.vm-view-list .vm-view').bind(event, function() {
jQuery(this).addClass(function() {
if(jQuery(this).hasClass('active')) return '';
return 'active';
});
jQuery(this).siblings('.vm-view').removeClass('active');
catalog_mode = jQuery(this).data('view');
display(catalog_mode);
});
});
var $_filtering = $('.ft-filtering', $element), _ft_opt_close = $('.ft-opt-close', $_filtering),
_filtering_clearall = $('.ft-filtering-clearall', $_filtering);
_ft_opt_close.on('click', function () {
var _data_value = $(this).parent().attr('data-filter'),
_cls_ft = $('.' + _data_value);
if (_cls_ft.length > 0) {
$(':checkbox', _cls_ft).removeAttr('checked');
$(_cls_ft).attr('value', '');
$('.ft-color-value', _cls_ft).removeClass('ft-checked');
processAjax();
}
});
_filtering_clearall.on('click', function () {
var _opt_inner = $('.ft-opt-inner', $_filtering);
if (_opt_inner.length > 0) {
_opt_inner.each(function () {
var _data_value = $(this).attr('data-filter'),
_cls_ft = $('.' + _data_value);
$(':checkbox', _cls_ft).removeAttr('checked');
$(_cls_ft).attr('value', '');
$('.ft-color-value', _cls_ft).removeClass('ft-checked');
});
processAjax();
}
});
}
})('#<?php echo $tag_id; ?>');
});
//]]>
</script>

Maps left top, not centered

When I'm clicking on add marker, the marker is in the top left of maps and not in the center.
I know that I'm working on V2, but I need it to work so I can get myself some time to figure V3 out.
Can someone please help me to fix this?
Already tried:
map.setCenter() on different places, but nothing works.
This is the main script:
<script
src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=<?php echo $this->params->get('map_api_key');?>"
type="text/javascript"></script>
<script type="text/javascript">
//<!--
var map;
var marker;
var markeradded=false;
var markerfixed=false;
var current_point;
var catIcon;
function initialize()
{
if (GBrowserIsCompatible())
{
map = new GMap2(document.getElementById("map_canvas"),{ size: new GSize(430, 315) });
map.setUIToDefault();
map.disableScrollWheelZoom();
geocoder = new GClientGeocoder();
map.checkResize()
}
}
window.addEvent('domready',function()
{
initialize();
//var mapSlider = new Fx.Slide('gb_maplocator', {duration: 1000});
var mapSlider = document.getElementById('gb_maplocator');
//var mapSlider = $('gb_maplocator');
<?php if( $this->data->published==0){?>
mapSlider.style.visibility = 'hidden';
mapSlider.style.height = '0px';
mapSlider.style.overflow = 'hidden';
<?php } ?>
$$('.gb_map_controls').addEvent('click',function(){
if(this.getProperty('value')==1)
{
mapSlider.style.visibility = 'visible';
mapSlider.style.height = 'auto';
}
else if(this.getProperty('value')==0)
{
mapSlider.style.visibility = 'hidden';
mapSlider.style.height = '0px';
mapSlider.style.overflow = 'hidden';
}
});
$('btnAddtomap').addEvent('click',
function(e) {
$('map_level').value=map.getZoom();
$('map_glat').value=current_point.lat();
$('map_glng').value=current_point.lng();
});
GEvent.addListener(map, "zoomend",
function(oldlevel,newlevel) {
$('map_level').value=newlevel;
});
GEvent.addListener(map, "dragend",
function() {
current_point=map.getCenter();
});
<?php
if( $this->pin->map_image )
{
?>
catIcon = new GIcon();
catIcon.image = '<?php echo JUri::root().$this->pin->map_image.".".$this->pin->extension;?>';
catIcon.shadow = '<?php echo JUri::root().$this->pin->shadow_image.".".$this->pin->extension;?>';
//catIcon.iconSize = new GSize(25.0, 32.0);
//catIcon.shadowSize = new GSize(42.0, 32.0);
catIcon.iconAnchor = new GPoint(12.0, 16.0);
catIcon.infoWindowAnchor = new GPoint(12.0, 16.0);
map.disableScrollWheelZoom();
<?php
}
if(abs($this->data->glat)==0&&abs($this->data->glng)==0)
{
$country=$mainframe->getUserState($option."countrytitle");
$region=$mainframe->getUserState($option."regiontitle");
$address= array();
if($region!= JText::_('ALL') && !empty($region)){
$address[]=$region;
}
if($country!= JText::_('ALL') && !empty($country)){
$address[]=$country;
}
array_filter ($address);
if(count($address)>0)
{
?>
showAddress('<?php echo implode(',',$address)?>');
<?php
}
else
{
?>
showAddress('<?php echo $this->params->get('map_default_address','Brisbane, Australia');?>');
<?php
}
}
else
{
if( ! $this->pin->map_image && $this->data->map_image )
{
?>
catIcon = new GIcon();
catIcon.image = '<?php echo JUri::root().$this->data->map_image.".".$this->data->extension;?>';
catIcon.shadow = '<?php echo JUri::root().$this->data->shadow_image.".".$this->data->extension;?>';
//catIcon.iconSize = new GSize(25.0, 32.0);
//catIcon.shadowSize = new GSize(42.0, 32.0);
catIcon.iconAnchor = new GPoint(12.0, 16.0);
catIcon.infoWindowAnchor = new GPoint(12.0, 16.0);
<?php }?>
current_point=new GLatLng(<?php echo $this->data->glat;?>,<?php echo $this->data->glng;?>);
map.setCenter(current_point,<?php echo $this->data->level;?>);
marker = new GMarker(current_point,{icon:catIcon,draggable:true});
GEvent.addListener(marker, "dragend",
function(latlng) {
current_point = latlng;
$('map_level').value=map.getZoom();
$('map_glat').value=latlng.lat();
$('map_glng').value=latlng.lng();
});
marker.disableDragging();
map.addOverlay(marker);
checkResize()
markeradded=true;
markerfixed=true;
$('addMarkerButton').disabled=true;
$('addMarkerButton').setHTML("<?php echo JText::_('REMOVE_MARKER');?>");
$('fixMarkerButton').setHTML("<?php echo JText::_('UNFIX_MARKER');?>");
$('map_level').value=map.getZoom();
$('map_glat').value=current_point.lat();
$('map_glng').value=current_point.lng();
<?php if($this->data->published==0){?>
mapSlider.style.visibility = 'hidden';
mapSlider.style.height = "0px";
mapSlider.style.overflow = 'hidden';
<?php }?>
<?php
}
?>
if(markeradded)
{
$('fixMarkerButton').disabled=false;
}
else
{
$('fixMarkerButton').disabled=true;
}
});
window.addEvent('unload',function(){GUnload()});
//-->
</script>
<div class="gb_madata_publish">
<label><?php echo JText::_('Activeer Google Maps');?>:</label><div class="gb_madata_publish_control"><?php echo $this->lists['status'];?></div>
</div>
<div class="gb_map_locator" id="gb_maplocator">
<a id="btnAddtomap"><?php echo JText::_('LOCATE_ADDRESS_TO_MAP');?></a>
<fieldset class="adminform"><input type="hidden" name="glat"
id="map_glat" /> <input type="hidden" name="glng" id="map_glng" /> <input
type="hidden" name="level" id="map_level" />
<div id="map_canvas" style="width: 430px; height: 315px"><script>checkResize() </script></div>
<br />
<div class="mapbuttons"><a id="addMarkerButton"><?php echo JText::_('ADD_MARKER');?></a>
<a id="fixMarkerButton"><?php echo JText::_('FIX_MARKER');?></a></div>
</fieldset>
</div>
<?php
}
?>
And this is the JavaScript file that is included:
/**
* Map controller buttons
*
*/
window.addEvent('domready', function() {
var country_id = '';
var region_id = '';
var address1 = '';
var address2 = '';
$('btnAddtomap')
.addEvent(
'click',
function(e) {
e = new Event(e);
e.stop();
if($('address1')== undefined && $('address2')== undefined) return false;
if($('country_id')!= undefined) country_id= $('country_id').value;
if($('region_id')!= undefined) region_id= $('region_id').value;
if($('address1')!= undefined) address1= $('address1').value;
if($('address2')!= undefined) address2= $('address2').value;
url = 'index.php?option=com_listbingo&format=raw&task=addons.map.admin.loadadd&cid='
+ country_id
+ '&region_id='
+ region_id;
url += '&street=' + address2
+ '&address='
+ address1;
req = new Ajax(url, {
onComplete :showAddress,
method :'get',
evalscript :true
});
req.request();
setCenter()
});
$('addMarkerButton').addEvent(
'click',
function(e) {
e = new Event(e);
e.stop();
if (!markeradded) {
marker = new GMarker(current_point, { icon:catIcon,
draggable :true
});
$('map_level').value=map.getZoom();
$('map_glat').value=(0);
$('map_glng').value=(0);
map.addOverlay(marker);
marker.enableDragging();
}
});
});
Done, i solved it by not using hidden divs.

Initializing google maps with multiple markers from an array

I'm passing 2 arrays into google maps, one for a location (which is geocoded) and another for that location's info window.
Is there any way I can initialize the map and plot all these points at once, or will I have to make a second function to plot more points? Since there are multiple points, I'm not sure how else to do it other than plotting one point, and then making an addition function which loops through the array and plots the rest.
Here's the code.
The two arrays(which I didn't include the code for) are $cityArray and $title
function initialize() {
geocoder = new google.maps.Geocoder();
latlang = geocoder.geocode( { 'address':
'<?php echo json_encode($cityArray); ?>'},
function(results, status) {
//use latlang to enter city instead of coordinates
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'click',
(function(marker, i) {
return function() {
infowindow.setContent(
'<?php echo json_encode($title); ?>'
);
infowindow.open(map, marker);
}
})(marker, i));
markersArray.push(marker);
}
else{
alert("Geocode was not successful for the following reason: "
+ status);
}
});
var myOptions = {
center: latlang, zoom: 4, mapTypeId: google.maps.MapTypeId.SATELLITE,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
};
var gm = google.maps;
map = new google.maps.Map(document.getElementById("main_Content"),
myOptions);
plotMarkers();
} //end of initialization function
var infowindow = new google.maps.InfoWindow();
Please refer the following Sample which i have used for the above.,
Step1 : Include the Three script Files in header of your page.,like
(i). <scrip type="text/javascript" src="http://maps.google.com/maps?file=api&v=2&key=Your_API_KEY"></script>
(ii).<scrip type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
(iii).<scrip type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js"></script>
Step2 : Scripts On Page
<script type="text/javascript">
//initialize the map window
jQuery(document).ready(function () {
load();
});
jQuery(window).unload(function () {
GUnload();
});
var map;
var geocoder;
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
function load() {
if (GBrowserIsCompatible()) {
geocoder = new GClientGeocoder();
map = new GMap2(document.getElementById('map'));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
//map.setCenter(new GLatLng(35.048629,-0.820663), 4);
searchLocations();
document.getElementById('directions-panel').innerHTML = '';
var url_new = ''+ benObj.TEMPLATE_DIR +'/print.html';
var print_icon_url_new = 'PrintLink';
jQuery('#print_icon').html(print_icon_url_new);
}
}
//Search Locations with address input
function searchLocations() {
var address = document.getElementById('addressInput').value;
// alert(address);
var address_new = jQuery("#addressInput_new").val();
if (address_new != "Enter City or Zip") {
jQuery("#loc1").html(address_new);
}
geocoder.getLatLng(address, function (latlng) {
//alert(latlng);
if (!latlng) {
alert(address + ' not found');
} else {
searchLocationsNear(latlng);
}
});
}
// Search Near By Location to place the Markers and Information windows
function searchLocationsNear(center) {
var radius = document.getElementById('radiusSelect').value;
var searchUrl = ''+ benObj.BASE_ROOT +'/mapmarker?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius + '&format=raw';
jQuery.get(searchUrl, function (data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName('marker');
map.clearOverlays();
var sidebar = document.getElementById('sidebar');
var sidebar_val = '';
//sidebar.innerHTML = 'Results Found';
jQuery("#sidebar").html(sidebar_val);
<!--jQuery("#loc_count").html(markers.length);-->
if (markers.length == 0) {
sidebar.innerHTML = 'No results found.';
map.setCenter(new GLatLng(35.048629, -0.820663), 4);
return;
}
var bounds = new GLatLngBounds();
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute('name');
var address = markers[i].getAttribute('address');
var phone_new = markers[i].getAttribute('phonenumber');
var distance = parseFloat(markers[i].getAttribute('distance'));
var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')), parseFloat(markers[i].getAttribute('lng')));
var markerchar = "b";
var marker = createMarker(point, name, address, phone_new);
map.addOverlay(marker);
// var location_count = jQuery('#loc_count').val();
jQuery('#loc_count').val(i + 1);
var sidebarEntry = createSidebarEntry(marker, name, address, distance, phone_new);
jQuery('#sidebar').append(sidebarEntry);
//sidebar.appendChild(sidebarEntry);
// ScrollPane.getContentPane().appendChild(sidebarEntry);
bounds.extend(point);
}
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
jQuery('#sidebar').jScrollPane();
//jQuery('#sidebar').reinitialise();
});
}
//To Create a Marker With Information Window
function createMarker(point, name, address, phone_new) {
var pinkIcon = new GIcon(G_DEFAULT_ICON);
pinkIcon.image = ""+ benObj.IMAGE_DIR +"addr-pin-1.png";
var markerOptions = {
icon: pinkIcon
};
var marker = new GMarker(point, markerOptions);
var event_calendar = "event_calendar";
var event_title = ""+ benObj.event_title +"";
var display = "block";
var e_dt_start = jQuery("#dtstart").val();
var e_dt_end = jQuery("#dtend").val();
var e_start_timestamp = (formatTimestring(e_dt_start));
var e_end_timestamp = (formatTimestring(e_dt_end));
var e_desc = jQuery("#edesc").val();
var StrippedString = e_desc.replace(/(<([^>]+)>)/ig, "");
var trimmed = StrippedString.replace(/^\s+|\s+$/g, '');
var html = '<b>' + name + '</b> <br/>' + address + '<br>contact: ' + phone_new + '<br><br>Add to Calendar<div class="summary" style="display:none;">' + event_title + ' - "' + name + '"</div><span class="dtstart date" title="' + e_dt_start + '" style="display:none;">8th Aug 2010</span><span class="dtend date" title="' + e_dt_end + '" style="display:none;">01:30am - 12:00pm</span><div class="event-desc" style="display:none;">' + trimmed + '</div><div class="event-locate" style="display:none;">' + name + ',' + address + '</div> | Remind Me<br><br>Get Direction From:<br><input type="hidden" id="start" value="' + address + '"><input type="text" id="end" value="" style="border: 1px solid #ECE6D5;"> <input type="button" value="GO" onclick="calcRoute();" style="border: 1px solid #ECE6D5;padding-left:5px;">';
GEvent.addListener(marker, 'click', function () {
marker.openInfoWindowHtml(html);
//jQuery(this).addtocal();
});
return marker;
}
// To Make Sidebar Entry If need
function createSidebarEntry(marker, name, address, distance, phone_new) {
var div = document.createElement('div');
var html = '<div class="locrow clearfix"><div class="left" style="width:240px;"><span class="count" id="loc_count">' + jQuery("#loc_count").val() + '</span><address><strong>' + name + '</strong>' + address + '</address><span class="mapdate"><span class="icon date"></span>'+ benObj.event_start_month_date +' – '+ benObj.event_end_month_date_year +'</span></div><div class="right" style="width:154px;"><ul><li><span class="icon phone"></span>' + phone_new + '</li><li><span class="icon time"></span>11 am – 7 pm</li><li><span class="icon car"></span>distance ' + distance.toFixed(1) + ' mi</li></ul></div></div>';
div.innerHTML = html;
div.style.cursor = 'pointer';
div.style.marginBottom = '5px';
GEvent.addDomListener(div, 'click', function () {
GEvent.trigger(marker, 'click');
});
GEvent.addDomListener(div, 'mouseover', function () {
div.style.backgroundColor = '#eee';
});
GEvent.addDomListener(div, 'mouseout', function () {
div.style.backgroundColor = '#fff';
});
return div;
}
// To make a Directions If need
function calcRoute() {
directionsDisplay = new google.maps.DirectionsRenderer();
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var url = "http://maps.google.co.in/maps?f=d&source=s_d&saddr=" + start + "&daddr=" + end + "&aq=0&vpsrc=0&hl=en&doflg=ptm&mra=ls&ie=UTF8&t=m&z=5&layer=c&pw=2";
var print_icon_url = 'PrintLink';
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var myOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(41.850033, -87.6500523)
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
directionsDisplay.setDirections(response);
jQuery('#print_icon').html(print_icon_url);
}
});
}
</script>
//To Create a XML For Markers and Information Windows
<?php
function mapMarker($center_lat,$center_lng,$radius)
{
$mysqli = $this->_getMySqlConnection();
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Search the rows in the markers table
$query = sprintf("SELECT phone,street_address_1, store_name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM locations HAVING distance < '%s' ORDER BY distance LIMIT 0 , 10",
$mysqli->real_escape_string($center_lat),
$mysqli->real_escape_string($center_lng),
$mysqli->real_escape_string($center_lat),
$mysqli->real_escape_string($radius));
$result = $mysqli->query($query);
header("Content-type: text/xml");
header('Access-Control-Allow-Origin: *');
$avoid_duplicate="";
// Iterate through the rows, adding XML nodes for each
while ($row = #$result->fetch_assoc())
{
if($avoid_duplicate!=$row['store_name'])
{
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name", $row['store_name']);
$newnode->setAttribute("address", $row['street_address_1']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("distance", $row['distance']);
$newnode->setAttribute("phonenumber", $row['phone']);
$avoid_duplicate=$row['store_name'];
}
}
$outXML=$dom->saveXML();
$result->close();
$mysqli->close();
return $outXML;
}
?>
HTML Part :
<div class="mapleft">
<div class="ScrollPane scroll-pane" id="sidebar" style="overflow: auto; height: 430px;"></div>
<div class="mapshadow"></div>
</div>
<input type="hidden" id="addressInput" value="<?php echo $zip_code;?>" />
<input type="hidden" id="radiusSelect" value="50" />
<input type="hidden" id="addressInput_temp" value="<?php echo $zip_code;?>" />
<input type="hidden" id="radiusSelect_temp" value="50" />
<input type="hidden" name="X_REQUESTED_WITH" value="XMLHttpRequest" />
<div class="mapright">
<div id="map" style="width: 475px; height: 450px"></div>
</div>
<div class="map-dir" id="directions-panel" style="float:right;width:488px;"></div>
<input type="hidden" id="loc_count" value="1" />
These are the things which will produce the great out comes.

How to get total value on dynamic value?

I have form like this :
<input type='hidden' name='seq' id='idseq' value='1' />
<div id='add_field' class='locbutton'><a href='#' title='Add'>Add</a></div>
<div id='remove_field' class='locbutton2'><a href='#' title='Delete'>Delete</a></div>
<div id="idcover">
1.<br />
<div class="group">
<div class="satu"><input type='text' name='score[1][]' id='score[1][]'></div>
<div class="dua"><input type='text' name='weight[1][]' id='weight[1][]'> %</div>
<div class="tiga"><input type='text' name='weightscore[1][]' id='weightscore[1][]'
disabled></div>
</div>
</div>
<br /><br />
<div id='idtotalcover' class='totalcover'>
Total <div class='total'><input type='text' name='total' id='idtotal' disabled /></div>
</div>
This is the jquery script:
<script type="text/javascript">
$(document).ready(
function ()
{
$("input[id^=score],input[id^=weight]").bind("keyup", recalc);
recalc();
var counter = $("#idseq").val();
$("#add_field").click(function ()
{
counter++;
$.ajax({
url: 'addinput.php',
dataType: "html",
data: "count="+counter,
success: function(data)
{
$('#idcover').append(data);
$('.dua input').keyup(function()
{
var $duaInput = $(this);
var weight=$duaInput.val();
var score=$duaInput.closest(".group").find('.satu input').val();
$.ajax({
url: "cekweightscore.php",
data: "score="+score+"&weight="+weight,
success:
function(data)
{
$duaInput.closest(".group").find('.tiga input').val(data);
}//success
});//ajax
});
}//success
});//ajax
});
});
function recalc()
{
var a=$("input[id^=score]");
var b=$("input[id^=weight]");
$("[id^=weightscore]").calc("(score * weight)/100",{score: a,weight: b},
function (s)
{
return s.toFixed(2);
},
function ($this){
//function($("[id^=weightscore]")){
// sum the total of the $("[id^=total_item]") selector
//alert($this);
//var sum = $this.sum();
var sum=$this.sum();
$("#idtotal").val(sum.toFixed(2));
}
);
}
</script>
This is the php code:
<?
$count=$_GET['count'];
echo"
<br>
$count
<div class='group' >
<div class='satu'>
<input type='text' name='score[$count][]' id='score[$count][]'>
</div>
<div class='dua'>
<input type='text' name='weight[$count][]' id='weight[$count][]'> %
</div>
<div class='tiga'>
<input type='text' name='weightscore[$count][]' id='weightscore[$count][]' disabled>
</div>
</div>";
?>
When I click the Add button, i cant get value on new form so that the new form cannot be calculated. What can i do to get total value on dynamic value ?
I remember reading this exact same question yesterday and I still have no idea of what you're trying to do.
Why are you adding inputs through AJAX instead of creating them in Javascript from the beginning? AJAX calls are expensive and are recommended to be used when you need to update/retrieve values from the server.
Why are you trying to do your calculations on the server side anyway? If you're dealing with dynamic input, you should be doing the calculations client side, then update the server when you're done.
Why do you use obscure name/id attribute values?
Anyway,
I created this example, it contains two different solutions, one with a ul and a table. Hopefully, the example matches what you're trying to do and might give you some insight.
I use a timer to update simulated server data. The timer is set to the variable update_wait. The other dynamic calculations are done client side.
I'll post the Javascript code as well, in case you don't like to fiddle
Example | Javascript
var update_server_timer = null,
update_wait = 1000; //ms
var decimals = 3;
/**********************
List solution
**********************/
function CreateListRow(){
var eLi = document.createElement("li"),
eScore = document.createElement("div"),
eWeight = document.createElement("div"),
eWeightScore = document.createElement("div");
var next_id = $("#cover li:not(.total)").length + 1
eScore.className = "score";
eWeight.className = "weight";
eWeightScore.className = "weightscore";
//Score element
var eScoreInput = document.createElement("input");
eScoreInput.type = "text";
eScoreInput.name = "score_"+next_id;
eScoreInput.id = "score_"+next_id;
eScore.appendChild(eScoreInput);
//Weight element
var eWeightInput = document.createElement("input");
eWeightInput.type = "text";
eWeightInput.name = "weight_"+next_id;
eWeightInput.id = "weight_"+next_id;
var eWeightPerc = document.createElement("div");
eWeightPerc.className = "extra";
eWeightPerc.innerHTML = "%";
eWeight.appendChild(eWeightInput);
eWeight.appendChild(eWeightPerc);
//Weightscore element
var eWeightScoreInput = document.createElement("input");
eWeightScoreInput.type = "text";
eWeightScoreInput.name = "weight_"+next_id;
eWeightScoreInput.id = "weight_"+next_id;
eWeightScore.appendChild(eWeightScoreInput);
$(eScore).keyup(function(){
CalculateListRow($(this).closest("li"));
});
$(eWeight).keyup(function(){
CalculateListRow($(this).closest("li"));
});
//item element
eLi.appendChild(eScore);
eLi.appendChild(eWeight);
eLi.appendChild(eWeightScore);
return eLi;
}
function CalculateListRowTotal(){
var fTotal = 0;
$("#cover li:not(.total) div:nth-child(3) input").each(function(){
var fVal = parseFloat($(this).val());
if(isNaN(fVal)) fVal = 0;
fTotal += fVal;
});
fTotal = parseFloat(fTotal.toFixed(decimals));
$("#cover li.total div input").val(fTotal);
//Update server variables here
RestartUpdateServerTimer();
}
function CalculateListRow($Li){
var fScore = parseFloat($("div.score input", $Li).val()),
fWeight = parseFloat($("div.weight input", $Li).val())/100,
fRes = (fScore*fWeight);
if(isNaN(fRes)) fRes = 0.00;
$("div.weightscore input", $Li).val(parseFloat(fRes.toFixed(decimals)));
CalculateListRowTotal();
}
$("#cover li div.weight input, #cover li div.score input").keyup(function(){
CalculateListRow($(this).closest("li"));
});
function AddListRow(){
$("#cover li.total").before(CreateListRow());
RestartUpdateServerTimer();
}
function RemoveListRow(){
$("#cover li.total").prev().remove();
CalculateListRowTotal();
}
$(".left_container .menu .add").click(function(){ AddListRow(); });
$(".left_container .menu .rem").click(function(){ RemoveListRow(); });
/**********************
Table solution
**********************/
function CreateTableRow(){
var eTr = document.createElement("tr"),
eTds = [document.createElement("td"),
document.createElement("td"),
document.createElement("td")];
var next_id = $("#cover2 tbody tr").length + 1;
$(eTds[0]).append(function(){
var eInput = document.createElement("input");
eInput.type = "text";
eInput.name = eInput.id = "score_"+next_id;
$(eInput).keyup(function(){
CalculateTableRow($(this).closest("tr"));
});
return eInput;
});
$(eTds[1]).append(function(){
var eRelativeFix = document.createElement("div"),
eInput = document.createElement("input"),
eExtra = document.createElement("div");
eRelativeFix.className = "relative_fix";
eInput.type = "text";
eInput.name = eInput.id = "weight_"+next_id;
eExtra.innerHTML = "%";
eExtra.className = "extra";
eRelativeFix.appendChild(eInput);
eRelativeFix.appendChild(eExtra);
$(eInput).keyup(function(){
CalculateTableRow($(this).closest("tr"));
});
return eRelativeFix;
});
$(eTds[2]).append(function(){
var eInput = document.createElement("input");
eInput.type = "text";
eInput.name = eInput.id = "weightscore_"+next_id;
return eInput;
});
for(i = 0; i < eTds.length; i++){
eTr.appendChild(eTds[i]);
}
return eTr;
}
function CalculateTableRowTotals(){
var $rows = $("#cover2 tbody tr"),
$totals = $("#cover2 tfoot tr th");
var fTotal = [];
//Each row
$rows.each(function(){
var $columns = $("td", this);
//Each column
$columns.each(function(i, e){
var fVal = parseFloat($("input", e).val());
if(isNaN(fVal)) fVal = 0;
if(isNaN(fTotal[i])) fTotal[i] = 0;
fTotal[i] += fVal;
});
});
for(i = 0; i < fTotal.length; i++){
fTotal[i] = parseFloat(fTotal[i].toFixed(decimals));
}
fTotal[1] = (fTotal[2]/fTotal[0]*100).toFixed(decimals)+"%";
fTotal[2] = parseFloat(fTotal[2].toFixed(decimals));
$totals.each(function(i, e){
$(this).text(fTotal[i]);
});
//Update server variables here
RestartUpdateServerTimer();
}
function CalculateTableRow($Tr){
var fScore = parseFloat($("td:nth-child(1) input", $Tr).val()),
fWeight = parseFloat($("td:nth-child(2) input", $Tr).val())/100,
fRes = (fScore*fWeight);
if(isNaN(fRes)) fRes = 0.00;
$("td:nth-child(3) input", $Tr).val(parseFloat(fRes.toFixed(decimals)));
CalculateTableRowTotals();
}
function AddTableRow(){
if($("#cover2 tbody tr").length == 0){
$("#cover2 tbody").append(CreateTableRow());
}else{
$("#cover2 tbody tr:last-child").after(CreateTableRow());
}
RestartUpdateServerTimer();
}
function RemoveTableRow(){
$("#cover2 tbody tr:last-child").remove();
CalculateTableRowTotals();
}
$(".right_container .menu .add").click(function(){ AddTableRow(); });
$(".right_container .menu .rem").click(function(){ RemoveTableRow(); });
$("#cover2 tbody tr td:nth-child(1) input, #cover2 tbody tr td:nth-child(2) input").keyup(function(){
CalculateTableRow($(this).closest("tr"));
});
/**********************
Server data
- Simulates the data on the server,
- whether it be in a SQL server or session data
**********************/
var ServerData = {
List: {
Count: 3,
Total: 5.50
},
Table: {
Count: 3,
Totals: [65, 8.46, 5.50]
}
};
function UpdateServerData(){
//List
var ListCount = $("#cover li:not(.total)").length,
ListTotal = $("#cover li.total input").val();
//Table
var TableCount = $("#cover2 tbody tr").length,
TableTotals = [];
$("#cover2 tfoot th").each(function(i, e){
TableTotals[i] = parseFloat($(this).text());
});
var data = {
json: JSON.stringify({
List: {
Count: ListCount,
Total: ListTotal
},
Table: {
Count: TableCount,
Totals: TableTotals
}
})
}
//Update
$.ajax({
url: "/echo/json/",
data: data,
dataType: "json",
type:"POST",
success: function(response){
ServerData.List = response.List;
ServerData.Table = response.Table;
var displist = "Server data<h1>List</h1><ul><li>Count: "+ServerData.List.Count+"</li><li>Total: "+ServerData.List.Total+"</li></ul>",
disptable = "<h1>Table</h1><ul><li>Count: "+ServerData.Table.Count+"</li>";
for(i=0; i<ServerData.Table.Totals.length; i++)
disptable += "<li>Total "+i+": "+ServerData.Table.Totals[i]+"</li>";
disptable += "</ul>";
$("#server_data").html(displist+"<br />"+disptable).effect("highlight");
}
});
}
function RestartUpdateServerTimer(){
if(update_server_timer != null) clearTimeout(update_server_timer);
update_server_timer = setTimeout(function(){
UpdateServerData()
}, update_wait);
}
UpdateServerData();
Update
Since you have a hard time grasping the concept, here's a copy paste solution that will work for you without having to use AJAX. I would like to point out that your HTML markup and general coding is a total mess...
Example | Code
<script type="text/javascript">
$(document).ready(function(){
function CreateInput(){
var $group = $("<div>"),
$score = $("<div>"),
$weight = $("<div>"),
$weightscore = $("<div>");
var group_count = $("div.group").length+1;
$group.addClass("group");
$score.addClass("satu");
$weight.addClass("dua");
$weightscore.addClass("tiga");
var $input_score = $("<input>"),
$input_weight = $("<input>"),
$input_weightscore = $("<input>")
$input_score
.attr("name", "score["+group_count+"][]")
.attr("type", "text")
.attr("id", "score["+group_count+"][]");
$input_weight
.attr("name", "weight["+group_count+"][]")
.attr("type", "text")
.attr("id", "weight["+group_count+"][]");
$input_weightscore
.attr("name", "weightscore["+group_count+"][]")
.attr("type", "text")
.attr("id", "weightscore["+group_count+"][]")
.attr("disabled", true);
$input_score.keyup(function(){
CalculateGroup($(this).parents(".group"));
});
$input_weight.keyup(function(){
CalculateGroup($(this).parents(".group"));
});
$score.append($input_score);
$weight.append($input_weight);
$weightscore.append($input_weightscore);
$group.append($score)
.append($weight)
.append($weightscore);
return $group;
}
function CalculateGroup($group){
var fScore = parseFloat($(".satu input", $group).val()),
fWeight = parseFloat($(".dua input", $group).val()),
fWeightScore = parseFloat((fScore*(fWeight/100)).toFixed(2));
if(isNaN(fWeightScore)) fWeightScore = 0;
$(".tiga input", $group).val(fWeightScore);
CalculateTotal();
}
function CalculateTotal(){
var fWeightScoreTotal = 0;
$("#idcover div.group div.tiga input").each(function(){
var fTotal = parseFloat(parseFloat($(this).val()).toFixed(2));
if(isNaN(fTotal)) fTotal = 0;
fWeightScoreTotal += fTotal;
});
fWeightScoreTotal = parseFloat(fWeightScoreTotal.toFixed(2));
$("#idtotalcover div.total input").val(fWeightScoreTotal);
}
$(".satu input, .dua input").keyup(function(){
CalculateGroup($(this).parents(".group"));
});
$("#add_field a").click(function(e){
$("#idcover").append(CreateInput());
e.preventDefault();
});
$("#remove_field a").click(function(e){
$("#idcover div.group:last-child").remove();
CalculateTotal();
e.preventDefault();
});
});
</script>

How to submit an iframe sub-form within main form using jQuery/AJAX?

I am using a jQuery plugin called Stepy, which is based of the FormToWizard plugin, to allow users to complete a 10-step form.
Using the next/back attributes, I've added a function to post data between steps so the user can save their work and come back at a later day if they'd like.
One of my steps allows the user to add items to a form within an iframe (to post data to a separate table). I'd like it to function so that when the user moves between steps, the items in the iframe post to their separate table as well. Is there a way to submit the form within the iframe between steps (i.e. submit iframe sub-form when main form submits)?
I am using PHP and MySQL.
Any help you could provide would be amazing!
Javascript:
$(function() {
$('#custom').stepy({
backLabel: 'Back',
block: true,
errorImage: true,
nextLabel: 'Next',
titleClick: true,
validate: false,
legend: false,
back: function(index) {
$.post('../../process.php')
}
next: function(index) {
$.post('../../process.php')
}
});
});
HTML:
<html>
<body>
<form id="custom" name="custom">
<fieldset title="Thread 1">
<legend>description one</legend>
<label>Question A:</label>
<input type="text" id="question_a" name="question_a" class="required">
<label>Question B:</label>
<input type="text" id="question_b" name="question_b">
</fieldset>
<fieldset title="Thread 2">
<legend>description two</legend>
<iframe src="../../list_form.php" width="100%" height="300"></iframe>
</fieldset>
<fieldset title="Thread 3">
<legend>description three</legend>
<label>Question C:</label>
<input type="text" id="question_c" name="question_c" class="required">
</fieldset>
<input type="submit" class="finish" value="Finish!">
</form>
</body>
</html>
iframe
<html>
<body>
<form id="sub_form" name="sub_form">
<label>Question 1:</label>
<input type="text" id="question_1" name="question_1">
<label>Question 2:</label>
<input type="text" id="question_2" name="question_2">
</form>
</body>
</html>
stepy.js
;(function($) {
var methods = {
init: function(options) {
return this.each(function() {
var opt = $.extend({}, $.fn.stepy.defaults, options),
$this = $(this).data('options', opt),
id = $this.attr('id');
if (id === undefined) {
id = 'stepy-' + $this.index();
$this.attr('id', id);
}
var $titlesWrapper = $('<ul/>', { id: id + '-titles', 'class': 'stepy-titles' });
if (opt.titleTarget) {
$(opt.titleTarget).html($titlesWrapper);
} else {
$titlesWrapper.insertBefore($this);
}
if (opt.validate) {
$this.append('<div class="stepy-error"/>');
}
var $steps = $this.children('fieldset'),
$step = undefined,
$legend = undefined,
description = '',
title = '';
$steps.each(function(index) {
$step = $(this);
$step
.addClass('step')
.attr('id', id + '-step-' + index)
.append('<p id="' + id + '-buttons-' + index + '" class="' + id + '-buttons"/>');
$legend = $step.children('legend');
if (!opt.legend) {
$legend.hide();
}
description = '';
if (opt.description) {
if ($legend.length) {
description = '<span>' + $legend.html() + '</span>';
} else {
$.error(id + ': the legend element of the step ' + (index + 1) + ' is required to set the description!');
}
}
title = $step.attr('title');
title = (title != '') ? '<div>' + title + '</div>': '--';
$titlesWrapper.append('<li id="' + id + '-title-' + index + '">' + title + description + '</li>');
if (index == 0) {
if ($steps.length > 1) {
methods.createNextButton.call($this, index);
}
} else {
methods.createBackButton.call($this, index);
$step.hide();
if (index < $steps.length - 1) {
methods.createNextButton.call($this, index);
}
}
});
var $titles = $titlesWrapper.children();
$titles.first().addClass('current-step');
var $finish = $this.children('.finish');
if (opt.finishButton) {
if ($finish.length) {
var isForm = $this.is('form'),
onSubmit = undefined;
if (opt.finish && isForm) {
onSubmit = $this.attr('onsubmit');
$this.attr('onsubmit', 'return false;');
}
$finish.click(function(evt) {
if (opt.finish && !methods.execute.call($this, opt.finish, $steps.length - 1)) {
evt.preventDefault();
} else {
if (isForm) {
if (onSubmit) {
$this.attr('onsubmit', onSubmit);
} else {
$this.removeAttr('onsubmit');
}
var isSubmit = $finish.attr('type') == 'submit';
if (!isSubmit && (!opt.validate || methods.validate.call($this, $steps.length - 1))) {
$this.submit();
}
}
}
});
$finish.appendTo($this.find('p:last'));
} else {
$.error(id + ': element with class name "finish" missing!');
}
}
if (opt.titleClick) {
$titles.click(function() {
var array = $titles.filter('.current-step').attr('id').split('-'), // TODO: try keep the number in an attribute.
current = parseInt(array[array.length - 1], 10),
clicked = $(this).index();
if (clicked > current) {
if (opt.next && !methods.execute.call($this, opt.next, clicked)) {
return false;
}
} else if (clicked < current) {
if (opt.back && !methods.execute.call($this, opt.back, clicked)) {
return false;
}
}
if (clicked != current) {
methods.step.call($this, (clicked) + 1);
}
});
} else {
$titles.css('cursor', 'default');
}
$steps.delegate('input[type="text"], input[type="password"]', 'keypress', function(evt) {
var key = (evt.keyCode ? evt.keyCode : evt.which);
if (key == 13) {
evt.preventDefault();
var $buttons = $(this).parent().children('.' + id + '-buttons');
if ($buttons.length) {
var $next = $buttons.children('.button right-aligned');
if ($next.length) {
$next.click();
} else {
var $finish = $buttons.children('.finish');
if ($finish.length) {
$finish.click();
}
}
}
}
});
$steps.first().find(':input:visible:enabled').first().select().focus();
});
}, createBackButton: function(index) {
var $this = this,
id = this.attr('id'),
opt = this.data('options');
$('<a/>', { id: id + '-back-' + index, href: 'javascript:void(0);', 'class': 'button left-aligned', html: opt.backLabel }).click(function() {
if (!opt.back || methods.execute.call($this, opt.back, index - 1)) {
methods.step.call($this, (index - 1) + 1);
}
}).appendTo($('#' + id + '-buttons-' + index));
}, createNextButton: function(index) {
var $this = this,
id = this.attr('id'),
opt = this.data('options');
$('<a/>', { id: id + '-next-' + index, href: 'javascript:void(0);', 'class': 'button right-aligned', html: opt.nextLabel }).click(function() {
if (!opt.next || methods.execute.call($this, opt.next, index + 1)) {
methods.step.call($this, (index + 1) + 1);
}
}).appendTo($('#' + id + '-buttons-' + index));
}, execute: function(callback, index) {
var isValid = callback.call(this, index + 1);
return isValid || isValid === undefined;
}, step: function(index) {
index--;
var $steps = this.children('fieldset');
if (index > $steps.length - 1) {
index = $steps.length - 1;
}
var opt = this.data('options');
max = index;
if (opt.validate) {
var isValid = true;
for (var i = 0; i < index; i++) {
isValid &= methods.validate.call(this, i);
if (opt.block && !isValid) {
max = i;
break;
}
}
}
$steps.hide().eq(max).show();
var $titles = $('#' + this.attr('id') + '-titles').children();
$titles.removeClass('current-step').eq(max).addClass('current-step');
if (this.is('form')) {
var $fields = undefined;
if (max == index) {
$fields = $steps.eq(max).find(':input:enabled:visible');
} else {
$fields = $steps.eq(max).find('.error').select().focus();
}
$fields.first().select().focus();
}
if (opt.select) {
opt.select.call(this, max + 1);
}
return this;
}, validate: function(index) {
if (!this.is('form')) {
return true;
}
var $step = this.children('fieldset').eq(index),
isValid = true,
$title = $('#' + this.attr('id') + '-titles').children().eq(index),
opt = this.data('options'),
$this = this;
$($step.find(':input:enabled').get().reverse()).each(function() {
var fieldIsValid = $this.validate().element($(this));
if (fieldIsValid === undefined) {
fieldIsValid = true;
}
isValid &= fieldIsValid;
if (isValid) {
if (opt.errorImage) {
$title.removeClass('error-image');
}
} else {
if (opt.errorImage) {
$title.addClass('error-image');
}
$this.validate().focusInvalid();
}
});
return isValid;
}
};
$.fn.stepy = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist!');
}
};
$.fn.stepy.defaults = {
back: undefined,
backLabel: '< Back',
block: false,
description: true,
errorImage: false,
finish: undefined,
finishButton: true,
legend: true,
next: undefined,
nextLabel: 'Next >',
titleClick: false,
titleTarget: undefined,
validate: false,
select: undefined
};
})(jQuery);
If you want to append Text\HTML or any other data to your iframe (which calling to a page on the same domain!) you may use:
jQuery("#iframe_id").contents().find('body').append('<div>Hello World</div>');
Full Example:
Full Example
If your iframe is on another domain you will have to use window.postMessage, which you may read about on Mozilla's docs:
Mozilla's docs
OR to take a look about my blog post about this subject.
Hope I helped,

Categories