Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New to the CF scene
    Join Date
    Jan 2013
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Live field updating script

    Hello,
    I am working on small project that requires this:

    have three fields:
    1. Basic price:
    2. NET price
    3. Gross price

    NET Price is determend by Profit margin rate
    Gross price is detremend by VAT rate

    I need to be able to "live" update all three fields no mater where is the input.

    e.g if I type in basic price Net price and gross price will update automaticly, or if typed Gross price Net price and basic price will update automaticly

    So far I have his:
    1. NET and gross price update:
    Code:
    function updateNet() {
    	if( document.adminForm.product_price_incl_tax.value != '' ) {
    		var taxRate = getTaxRate();
    
    		var r = new RegExp("\,", "i");
    		document.adminForm.product_price_incl_tax.value = document.adminForm.product_price_incl_tax.value.replace( r, "." );
    
    		var netValue = document.adminForm.product_price_incl_tax.value;
    
    		if (taxRate > 0) {
    			netValue = netValue / (taxRate + 1);
    		}
    
    		document.adminForm.product_price.value = doRound(netValue, 5);
    	}
    }

    2. gross and NET price update:
    Code:
    function updateGross() {
    	if( document.adminForm.product_price.value != '' ) {
    		var taxRate = getTaxRate();
    
    		var r = new RegExp("\,", "i");
    		document.adminForm.product_price.value = document.adminForm.product_price.value.replace( r, "." );
    
    		var grossValue = document.adminForm.product_price.value;
    
    		if (taxRate > 0) {
    			grossValue = grossValue * (taxRate + 1);
    		}
    
    		document.adminForm.product_price_incl_tax.value = doRound(grossValue, 5);
    	}
    }

    3. Basic and NET price update:
    Code:
    function updateProfit() {
    	if( document.adminForm.product_profitmargin_price.value != '' ) {
    		var profitRate = getProfitRate();
    
    		var r = new RegExp("\,", "i");
    		document.adminForm.product_profitmargin_price.value = document.adminForm.product_profitmargin_price.value.replace( r, "." );
    		document.adminForm.product_price_incl_tax.value = document.adminForm.product_price_incl_tax.value.replace( r, "." );
    
    		var netValue = document.adminForm.product_profitmargin_price.value;
    
    		if (profitRate > 0) {
    			netValue = netValue * (profitRate + 1);
    		}
    		document.adminForm.product_price.value = doRound(netValue, 5);
    	}
    }
    so I am missing as described above, possibility to update all three fields at once and currently stacked with this partial solution

    Any help is highly appreciated.

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,302
    Thanks
    203
    Thanked 2,562 Times in 2,540 Posts
    Here is one possible approach:-


    Code:
    <form id =  "adminForm">
    Basic <Input type = "text" id = "basic" onchange = "update(1)"><br>
    Net <input type = "text" id = "net" onchange = "update(2)"><br>
    Gross <input type = "text" id = "gross" onchange = "update(3)"><br>
    </form>
    
    <script type = "text/javascript">
    var profitmargin = .25;
    var vatrate = .2;  // presumably these two values are constants
    
    function update (x) {
    var b = document.getElementById("basic");
    var n = document.getElementById("net");
    var g = document.getElementById("gross");
    
    if (x==1) {
    b.value = (b.value*1).toFixed(2);
    n.value = (b.value * (1 + profitmargin)).toFixed(2);
    g.value = (n.value * (1 + vatrate)).toFixed(2);
    }
    
    if (x==2) {
    n.value = (n.value*1).toFixed(2);
    b.value = (n.value / (1 + profitmargin)).toFixed(2);
    g.value = (n.value * (1 + vatrate)).toFixed(2);
    }
    
    if (x==3) {
    g.value = (g.value*1).toFixed(2);
    n.value = (g.value / (1 + vatrate)).toFixed(2);
    b.value = (n.value / (1 + profitmargin)).toFixed(2);
    }
    
    }
    </script>

    Note that forms should be assigned an id, not a name which is now deprecated and obsolete. Form elements should be referenced by id.

    Quizmaster: "I'm just going outside, and may be some time" were the last words of which explorer?
    Contestant: Columbus
    Last edited by Philip M; 01-23-2013 at 09:36 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    Beginner1 (01-23-2013)

  • #3
    New to the CF scene
    Join Date
    Jan 2013
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Thank you Philip M,
    is it possible to do it in same manner as code that I posted?

    VAT and Margin are not constants.

    Please find bellow complete script:

    Code:
    <script type="text/javascript">
    //<!--
    function toggleDisable( elementOnChecked, elementDisable, disableOnChecked ) {
    	try {
    		if( !disableOnChecked ) {
    			if(elementOnChecked.checked==true) {
    				elementDisable.disabled=false;
    			}
    			else {
    				elementDisable.disabled=true;
    			}
    		}
    		else {
    			if(elementOnChecked.checked==true) {
    				elementDisable.disabled=true;
    			}
    			else {
    				elementDisable.disabled=false;
    			}
    		}
    	}
    	catch( e ) {}
    }
    // Modification.
    // All rights reserved.
    var tax_rates = new Array();
    var profit_rates = new Array();
    <?php
    foreach( $profit_rates as $profit_rate_id => $profit_rate ) {
    	echo "profit_rates[\"$profit_rate_id\"] = $profit_rate;\n";
    }
    ?>
    <?php
    foreach( $tax_rates as $tax_rate_id => $tax_rate ) {
    	echo "tax_rates[\"$tax_rate_id\"] = $tax_rate;\n";
    }
    ?>
    function doRound(x, places) {
    	return Math.round(x * Math.pow(10, places)) / Math.pow(10, places);
    }
    
    function getTaxRate() {
    	var selected_value = document.adminForm.product_tax_id.selectedIndex;
    	var parameterVal = document.adminForm.product_tax_id[selected_value].value;
    
    	if ( (parameterVal > 0) && (tax_rates[parameterVal] > 0) ) {
    		return tax_rates[parameterVal];
    	} else {
    		return 0;
    	}
    }
    <!--vmelektronik changed for profit margn-->
    function getProfitRate() {
    	var selected_value = document.adminForm.product_profit_id.selectedIndex;
    	var parameterVal = document.adminForm.product_profit_id[selected_value].value;
    
    	if ( (parameterVal > 0) && (profit_rates[parameterVal] > 0) ) {
    		return profit_rates[parameterVal];
    	} else {
    		return 0;
    	}
    }
    <!--end of vmelektronik changed for profit margn-->
    //changed by vmelektronik for profit margin.
    function updateProfit() {
    	if( document.adminForm.product_profitmargin_price.value != '' ) {
    		var profitRate = getProfitRate();
    
    		var r = new RegExp("\,", "i");
    		document.adminForm.product_profitmargin_price.value = document.adminForm.product_profitmargin_price.value.replace( r, "." );
    		document.adminForm.product_price_incl_tax.value = document.adminForm.product_price_incl_tax.value.replace( r, "." );
    
    		var netValue = document.adminForm.product_profitmargin_price.value;
    
    		if (profitRate > 0) {
    			netValue = netValue * (profitRate + 1);
    		}
    		document.adminForm.product_price.value = doRound(netValue, 5);
    	}
    }
    // end of profit margin change
    function updateGross() {
    	if( document.adminForm.product_price.value != '' ) {
    		var taxRate = getTaxRate();
    
    		var r = new RegExp("\,", "i");
    		document.adminForm.product_price.value = document.adminForm.product_price.value.replace( r, "." );
    
    		var grossValue = document.adminForm.product_price.value;
    
    		if (taxRate > 0) {
    			grossValue = grossValue * (taxRate + 1);
    		}
    
    		document.adminForm.product_price_incl_tax.value = doRound(grossValue, 5);
    	}
    }
    
    function updateNet() {
    	if( document.adminForm.product_price_incl_tax.value != '' ) {
    		var taxRate = getTaxRate();
    
    		var r = new RegExp("\,", "i");
    		document.adminForm.product_price_incl_tax.value = document.adminForm.product_price_incl_tax.value.replace( r, "." );
    
    		var netValue = document.adminForm.product_price_incl_tax.value;
    
    		if (taxRate > 0) {
    			netValue = netValue / (taxRate + 1);
    		}
    
    		document.adminForm.product_price.value = doRound(netValue, 5);
    	}
    }
    
    function updateDiscountedPrice() {
    	if( document.adminForm.product_price.value != '' ) {
    		try {
    			var selected_discount = document.adminForm.product_discount_id.selectedIndex;
    			var discountCalc = document.adminForm.product_discount_id[selected_discount].id;
    			<?php if( PAYMENT_DISCOUNT_BEFORE == '1' ) : ?>
    			var origPrice = document.adminForm.product_price.value;
    			<?php else : ?>
    			var origPrice = document.adminForm.product_price_incl_tax.value;
    			<?php endif; ?>
    
    			if( discountCalc ) {
    				eval( 'var discPrice = ' + origPrice + discountCalc );
    				if( discPrice != origPrice ) {
    					document.adminForm.discounted_price_override.value = discPrice.toFixed( 2 );
    				} else {
    					document.adminForm.discounted_price_override.value = '';
    				}
    			}
    		}
    		catch( e ) { }
    	}
    }
    function toggleProductList( enable ) {
    	if(enable) {		
        	document.getElementById('list_style0').disabled = false;
           document.getElementById('list_style0').checked = true;
        	document.getElementById('list_style1').disabled = false;
           document.getElementById('display_headers').disabled = false;
        	document.getElementById('product_list_child').disabled = false;
           document.getElementById('product_list_type').disabled = false;
    	}
        else {
        	document.getElementById('list_style0').disabled = true;
        	document.getElementById('list_style1').disabled = true;
           document.getElementById('display_headers').disabled = true;
        	document.getElementById('product_list_child').disabled = true;
           document.getElementById('product_list_type').disabled = true;
           document.getElementById('display_headers').checked = false;
        	document.getElementById('product_list_child').checked = false;
           document.getElementById('product_list_type').checked = false;
    	}
    }
    updateGross();
    updateDiscountedPrice();
    updateProfit();
    <?php
    if( @$_REQUEST['no_menu'] != '1') {
    	?>
    	toggleDisable( document.adminForm.product_full_image_action[1], document.adminForm.product_thumb_image, true );
    	<?php
    }
    ?>
    var productSearchField = function(){
    
        var relds = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({
                url: 'index2.php?option=com_virtuemart&page=product.ajax_tools&task=getproducts&ajax_request=1&func=&no_menu=1&only_page=1&no_html=1&product_id=<?php echo $product_id ?>',
                method: 'GET' }),
            reader: new Ext.data.JsonReader({
                root: 'products',
                totalProperty: 'totalCount',
                id: 'product_id'
    	        }, [
    	            {name: 'product'},
    	            {name: 'category'},
    	            {name: 'product_id'}
    	        ])
        });   
        // Custom rendering Template
        var resultTpl = new Ext.XTemplate( '<tpl for="."><div class="x-combo-list-item">{category} / {product}</div></tpl>' );
        relatedSelection = document.getElementById('relatedSelection');
        related_products = document.adminForm.related_products;
        var relProdSearch = new Ext.form.ComboBox({
        	applyTo: 'relatedProductSearch',
            store: relds,
            title: '<?php echo addslashes($VM_LANG->_('VM_PRODUCT_SELECT_ONE_OR_MORE')); ?>',
            displayField:'product',
            typeAhead: false,
            loadingText: '<?php echo addslashes($VM_LANG->_('VM_PRODUCT_SEARCHING')); ?>',
            width: 270,
            minListWidth: 270,
            pageSize:15,
            emptyText: "<?php  echo addslashes($VM_LANG->_('PHPSHOP_SEARCH_TITLE')); ?>",
            tpl: resultTpl,
            onSelect: function(record) {
            	for(var i=0;i<relatedSelection.options.length;i++) {
            		if(relatedSelection.options[i].value==record.id) {
            			return;
            		}
            	}
            	o = new Option( record.data.product, record.id );
            	relatedSelection.options[relatedSelection.options.length] = o;
            	if( related_products.value != '') {
            		related_products.value += '|' + record.id;
            	} else {
            		related_products.value += record.id;
            	}
            }
        });
    	
    };
    var categorySearchField = function(){
    
        var relds = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({
                url: 'index2.php?option=com_virtuemart&page=product.ajax_tools&task=getcategories&ajax_request=1&func=&no_menu=1&only_page=1&no_html=1',
                method: 'GET'            
            }),
            reader: new Ext.data.JsonReader({
                root: 'categories',
                totalProperty: 'totalCount',
                id: 'category_id'
    	        }, [
    	            {name: 'category'},
    	            {name: 'category_id'}
    	        ])
        });
       
        // Custom rendering Template
        var resultTpl = new Ext.XTemplate(
        	'<tpl for="."><div class="x-combo-list-item">{category} (ID: {category_id})</div></tpl>'
        );
        relatedCatSelection = document.getElementById('relatedCatSelection');
        category_ids = document.adminForm.category_ids;
        var relProdSearch = new Ext.form.ComboBox({
        	applyTo: "categorySearch",
            store: relds,
            title: '<?php echo addslashes($VM_LANG->_('VM_PRODUCT_SELECT_ONE_OR_MORE')); ?>',
            displayField:'category',
            typeAhead: false,
            loadingText: '<?php echo addslashes($VM_LANG->_('VM_PRODUCT_SEARCHING')); ?>',
            width: 170,
            minListWidth: 170,
            pageSize:15,
            emptyText: "<?php  echo addslashes($VM_LANG->_('PHPSHOP_SEARCH_TITLE')); ?>",
            tpl: resultTpl,
            onSelect: function(record) {
            	for(var i=0;i<relatedCatSelection.options.length;i++) {
            		if(relatedCatSelection.options[i].value==record.id) {
            			return;
            		}
            	}
            	o = new Option( record.data.category, record.id );
            	
            	relatedCatSelection.options[relatedCatSelection.options.length] = o;
            	if( category_ids.value != '') {
            		category_ids.value += '|' + record.id;
            	} else {
            		category_ids.value += record.id;
            	}
            }
        });
    	
    };
    if( Ext.isIE6 || Ext.isIE7 ) {
    	Ext.EventManager.addListener( window, 'load', productSearchField );
    	if( Ext.get("categorySearch") ) {
    		Ext.EventManager.addListener( window, 'load', categorySearchField );
    	}
    }
    else {
    	Ext.onReady( productSearchField );
    	if( Ext.get("categorySearch") ) {
    		Ext.onReady( categorySearchField );
    	}
    }
    function removeSelectedOptions(from, hiddenField ) {
    	field = eval( "document.adminForm." + hiddenField );
    	// Delete them from original
    	var newOptions = [];
    	for (var i=(from.options.length-1); i>=0; i--) {
    		var o = from.options[i];
    		if (o.selected) {
    			from.options[i] = null;
    		} else {
    			newOptions.push(o.value);
    		}
    	}
    	field.value = newOptions.join('|');
    	
    }
    //-->
    </script>
    Last edited by Beginner1; 01-23-2013 at 10:12 AM.

  • #4
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,302
    Thanks
    203
    Thanked 2,562 Times in 2,540 Posts
    Quote Originally Posted by Beginner1 View Post
    Thank you Philip M,
    is it possible to do it in same manner as code that I posted?

    VAT and Margin are not constants.
    Not sure what you mean by "the same manner as the code that you posted", but this forum is not a free coding service. Your (overly complicated) code requires considerable re-writing. You can tell its great age by the hiding tags. The <!-- and //--> comment (hiding) tags have not been necessary since IE3 (i.e. since September 1997). If you see these in some published script it is a warning that you are looking at ancient and perhaps unreliable code. I notice that you are using eval() (regarded by some as evil ) and refer to the now-defunct IE6.

    As this is a commercial application I would suggest you pay a professional to do the job. But you could easily modify my code to allow for differing profit and tax rates obtained from select lists - you gave no clue about these in your original post.
    Last edited by Philip M; 01-23-2013 at 12:21 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •