How can I stop page jumping to top after form submission

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • razar63
    New Member
    • Nov 2014
    • 2

    How can I stop page jumping to top after form submission

    Hi I have modified a simple shopping cart tutorial which works fine however after the item is added to the cart it jumps to the top of the page. I have tried using the preventDefault command but it dosn't work.

    Code:
    <script type="javascript">
    	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script language="javascript">
    function addtocart(pid){
        document.form1.productid.value=pid;
        document.form1.command.value='add'; 
        document.form1.submit((function(e){  
           // Cancel the default action
           e.preventDefault();  
    })) ; 
        confirm('You have just added another item to the cart ') ;
    	
    }
    </script>
    The add to cart function code looks like this
    Code:
    function addtocart($pid,$q){
    		if($pid<1 or $q<1) return;
    		
    		if(is_array($_SESSION['cart'])){
    			if(product_exists($pid)) return;
    			$max=count($_SESSION['cart']);
    			$_SESSION['cart'][$max]['productid']=$pid;
    			$_SESSION['cart'][$max]['qty']=$q;
    		}
    		else{
    			$_SESSION['cart']=array();
    			$_SESSION['cart'][0]['productid']=$pid;
    			$_SESSION['cart'][0]['qty']=$q;
    		}
    	}
    	function product_exists($pid){
    		$pid=intval($pid);
    		$max=count($_SESSION['cart']);
    		$flag=0;
    		for($i=0;$i<$max;$i++){
    			if($pid==$_SESSION['cart'][$i]['productid']){
    				$flag=1;
    				break;
    			}
    		}
    		return $flag;
    	}
    What can I do to prevent the jump to the top of the page after adding an item to the cart?
    Last edited by razar63; Nov 17 '14, 08:00 AM. Reason: spelling mistake
  • Claus Mygind
    Contributor
    • Mar 2008
    • 571

    #2
    Had the same problem once. Was fully explained after I posted the question in this forum.

    Most likely you are executing from an anchor on the page. So you need to remove the # or href="" from the anchor. This in turn will mean you need to create css style so you link looks like a link

    Code:
    <a [B]class="simAnchor"[/B] id="'+thisId+'" onclick="useThisId(this, '+c.cFieldName+');">'+thisId+'</a>

    Comment

    • razar63
      New Member
      • Nov 2014
      • 2

      #3
      Thanks Claus
      I did something similar by redirecting back to a dynamic anchor point on the page. Much easier than trying to get the same result battling with javascript.

      Comment

      Working...