jQuery preventDefault doesn't always work


myhappycoding

I have a function called showBasket that shows you a list of items added to shoppingBasket. This happens whenever the user clicks the link. Every time you click outside the menu, it hides again.

My problem is that in this menu I have a list of links related to each item and you can delete the selected item. This link sometimes works fine, or works differently depending on the web browser I'm using.

what i want is to delete the item without refreshing the whole page so i think i have to do something with the preventDefaultlink and when i debug the code i see it repeats a lot of times so something is wrong especially when i look at Until sometimes I don't get the desired result.

As you can see, I'm using two Ajax functions, one that deletes the item I think is working, and the other that refreshes the data.

It would be great if someone could help me. I stand by this.

/*
SHOWS AND HIDE A BASKET MENU, EVERYTIME YOU CLICK IN THE SELECTED LINK
THIS MENU SHOWS A LIST OF ARTICLES ADDED TO A SHOPPING BASKET, AND EACH ITEM OF THE LIST
HAS A LINK THAT ALLOWS YOU TO DELETE THE SELECTED ITEM.

*/

function showBasket(){
    var $basket=$('#basket');
    var nstyle=$basket.css("display");
    $basket.on('click','a[title="delete article"]',function(e){
    e.preventDefault();
        del($(this));
        updateBasket($(this));

        function del(m){
            var n=m.attr("href");
            n=n.split("=");
            var l=n[1];
            $.ajax({
                type:"GET",
                data:{productoRemoveId:l},
            });
            return false;
        }

        function updateBasket(m){
            $.ajax({
                url:'updateBasket.php',
                success: function(response){
                    $cesta.html(response);
                }
            });
            return false;
        }
        return false;
    });
    if (nstyle=='none'){
        $basket.fadeIn(false,function(){//showing the basket
            $('html').bind("click",function(){
                $basket.fadeOut();//hidding the basket
                $("html").unbind("click");
            });
        });
    }
}

Here is the HTML code, relative to the script above:

<div id="basket" class="box_menu" style="display: table;">  <div class="row header">
    <h1>Mi cesta</h1>
        <span>3 articulos añadidos)</span>  
</div>
    <div class="detalle">
        <div class="row">
            <div class="celda_detalle"><input type="text" name="tecantidad" maxlength="3" value="1"></div>
            <div class="celda_detalle"><span>lechuga</span></div>
            <div class="celda_detalle"><span>9.25</span></div>
            <div class="celda_detalle"><a title="delete article" href="./bienvenida.php?productoRemove=5">Eliminar Articulo</a></div>
        </div>
        <div class="row">
            <div class="celda_detalle"><input type="text" name="tecantidad" maxlength="3" value="1"></div>
            <div class="celda_detalle"><span>Lejia</span></div>
            <div class="celda_detalle"><span>8.23</span></div>
            <div class="celda_detalle"><a title="delete article" href="./bienvenida.php?productoRemove=2">Eliminar Articulo</a></div>
        </div>
        <div class="row">
            <div class="celda_detalle"><input type="text" name="tecantidad" maxlength="3" value="1"></div>
            <div class="celda_detalle"><span>limones</span></div>
            <div class="celda_detalle"><span>8.25</span></div>
            <div class="celda_detalle"><a title="delete article" href="./bienvenida.php?productoRemove=3">Eliminar Articulo</a></div>
        </div>
    </div>
        <div class="fila pie">
            <div class="celda_pie">
                <span>Subtotal: 25.73€</span>
            </div>
            <div class="celda_pie">
                <a title="Save Shopping" href="#">Save Shopping</a>
            </div>
            <div class="celda_pie">
                <a title="Pay Shopping" href="#">Pay Shopping</a>
            </div>
</div></div>

I've tried translating the main code into English, so if you find any bugs please let me know.

I won't post the entire PHP code, but I'll post the most relevant code:

ShoppingCart class implements Iterator, Countable {

// Array stores the list of items in the cart:
protected $items = array();

// For tracking iterations:
protected $position = 0;

// For storing the IDs, as a convenience:
protected $ids = array();

private $subtotal  = 0;
private $itemCount = 0;

//MORE CODE ....
// Removes an item from the cart:
public function deleteItem($id) {

    // Need the unique item id:
        //$id = $item->getId();

    // Remove it:
    if (isset($this->items[$id])) {
        unset($this->items[$id]);

        // Remove the stored id, too:
        $index = array_search($id, $this->ids);
        unset($this->ids[$index]);

        // Recreate that array to prevent holes:
        $this->ids = array_values($this->ids);

    }

    $this->itemCount=$this->count();

    $this->subtotal=$this->calcularTotal();
    return true;

} // End of deleteItem() method.

public function display_cart() {
    ////////////////////////////////////////////////////////////////////////
    // Output the cart

    // Return specified number of tabs to improve readability of HTML output
    function tab($n) {
        $tabs = null;
        while ($n > 0) {
            $tabs .= "\t";
            --$n;
        }
        return $tabs;
    }

    if (isset($_GET['productoRemove']))
        if($_GET['productoRemove'] && !$_POST) {
            $idp=$_GET['productoRemove'];
            $this->deleteItem($idp);
        }


    // Display the cart header
    echo tab(1) . "<div class='row header'>\n";
    echo tab(1) . "<h1>Mi cesta</h1>\n";
    echo tab(2) . "<span>". $this->count()." articles added)</span>";
    echo tab(1) . "</div>\n";
    echo tab(1) . "<div class='detalle'>";
    if ($this->count()==0){
        echo tab(2) . "<div class='row'>";
        echo tab(3) . "<span style='display:table-cell; width:450px; vertical-align:middle; text-align:center; color:#666; font-style:italic; font-size:12px;'>La cesta está vacía</span>";
        echo tab(2) . "</div>\n";
    } else {
        //$producto=$this->current();
        $lista=$this->getItems();
        foreach ($lista as $producto){
            echo tab(2) . "<div class='fila' class=".$producto['item']->getId().">\n";
            echo tab(3) . "<div class='celda_detalle'><input type='text' name='tecantidad' maxlength='3' value='".$producto['qty']."'></div>";
            echo tab(3) . "<div class='celda_detalle'><span>".$producto['item']->getNombre()."</span></div>";
            echo tab(3) . "<div class='celda_detalle'><span>".$producto['item']->getPrecio()."</span></div>";
            echo tab(3) . "<div class='celda_detalle'><a title='delete article' href='./bienvenida.php?productoRemove=".$producto['item']->getId()."'>Eliminar Articulo</a></div>";
            echo tab(2) . "</div>\n";
        }
    }
    echo tab(1) . "</div>\n";
    echo tab(2) . "<div class='fila pie'>";
    echo tab(3) . "<div class='celda_pie'>";
    echo tab(4) . "<span>Subtotal: ".$this->calcularTotal()."€</span>";
    echo tab(3) . "</div>\n";
    echo tab(3) . "<div class='celda_pie'>";
    echo tab(4) . "<a title='Save Shopping' href='#'>Save Shopping</a>";
    echo tab(3) . "</div>\n";
    echo tab(3) . "<div class='celda_pie'>";
    echo tab(4) . "<a title='Finish Shopping' href='#'>Finish Shopping</a>";
    echo tab(3) . "</div>\n";
}
}
// Start a new session in case it hasn't already been started on the including page
@session_start();

// Initialize jcart after session start
if (empty($_SESSION['carrito']))
    $carrito="";
else
    $carrito = $_SESSION['carrito'];
if(!is_object($carrito)) {
    $carrito = $_SESSION['carrito'] = new ShoppingCart();
}

To better understand what I got, I also show a photo:

enter image description here

My inspiration for the code came from the following code:

http://conceptlogic.com/jcart/

Mohsen Dorparasti

1 e.preventDefault()- should be the first function to be called.

2- IE has a different syntax for this:

 event.returnValue = false;

Check here .

Related


jQuery preventDefault doesn't always work

myhappycoding I have a function called showBasket that shows you a list of items added to shoppingBasket. This happens whenever the user clicks the link. Every time you click outside the menu, it hides again. My problem is that in this menu I have a list of li

jQuery preventDefault() doesn't work with .on()

Mr Gandy Yes, I've read many other articles with the same problem, but I don't understand how to fix this. I have created a bookmark button that needs to change the icon when clicked. my jQuery: jQuery(document).ready( function() { var bm = jQuery(".u

jQuery preventDefault() doesn't work with .on()

Mr Gandy Yes, I've read many other articles with the same problem, but I don't understand how to fix this. I have created a bookmark button that needs to change the icon when clicked. my jQuery: jQuery(document).ready( function() { var bm = jQuery(".u

jQuery preventDefault() doesn't work with .on()

Mr Gandy Yes, I've read many other articles with the same problem, but I don't understand how to fix this. I have created a bookmark button that needs to change the icon when clicked. my jQuery: jQuery(document).ready( function() { var bm = jQuery(".u

jQuery preventDefault() doesn't work with .on()

Mr Gandy Yes, I've read many other articles with the same problem, but I don't understand how to fix this. I have created a bookmark button that needs to change the icon when clicked. my jQuery: jQuery(document).ready( function() { var bm = jQuery(".u

jQuery preventDefault() doesn't work with .on()

Mr Gandy Yes, I've read many other articles with the same problem, but I don't understand how to fix this. I have created a bookmark button that needs to change the icon when clicked. my jQuery: jQuery(document).ready( function() { var bm = jQuery(".u

jQuery preventDefault() doesn't work in AJAX call

coronavirus disease So when the user enters an email, I'm checking if that email exists. $('form.recover-form#check-form').on('submit', function(e){ var form = $(this), input = $('.check-recover-email'), span = $('.recover-error')

jQuery .click() event.preventDefault() doesn't work

Richard King: I'm building an extensible web application by putting scripts into a preset directory. The script needs to read the file header before going to the page, so I need to use .preventDefault() when I click the link and run some JScript first. Unfortu

jQuery's preventDefault doesn't work with generated forms

Signal I am trying to generate a form by clicking on a list of users and post the data using AJAX. The preventDefaultelement does not work. I want to validate the form using AJAX without reloading the page. my code: $(function(){ $("#members_list ul > li")

jQuery .click() event.preventDefault() doesn't work

Richard King: I'm building an extensible web application by putting scripts into a preset directory. The script needs to read the file header before going to the page, so I need to use .preventDefault() when I click the link and run some JScript first. Unfortu

jQuery .click() event.preventDefault() doesn't work

Richard King I'm building an extensible web application by putting scripts into a preset directory. The script needs to read the file header before going to the page, so I need to use .preventDefault() when I click the link and run some JScript first. Unfortun

jQuery event.preventDefault() doesn't work unless debugging

metal encoder I am trying to use this method in order to convert GET parameters to POST. I also want the anchors to be handled correctly even when the middle mouse button is clicked. This is how the event handler is bound: $(document).ready(function () { $

JQuery 2.1.4 preventDefault on form submit doesn't work

salipshitz I have an HTML form that I'm trying to handle with JQuery 2.1.4 by using event.preventDefault() in the .on('submit', function(event) {})method , but it just reloads even though I'm event.preventDefault()there. Here is my HTML, CSS and JS code: var g

jQuery UI tab beforeLoad preventDefault doesn't work

Judge God Somehow the e.preventDefault()on beforeLoad()event in jQuery UI Tabs is not working properly. Here is a small example: <div id="tabs"> <ul> <li><a href="#exampleExistingTab">Existing Tab</a></li> <li><a href="/path/to/remote/tab">

jQuery UI tab beforeLoad preventDefault doesn't work

Judge God The e.preventDefault()on beforeLoad()event in jQuery UI Tabs is not working properly. Here is a small example: <div id="tabs"> <ul> <li><a href="#exampleExistingTab">Existing Tab</a></li> <li><a href="/path/to/remote/tab">Remote T

jQuery preventDefault doesn't work after field validation

Jules The following code is designed to validate that the input is not Blankt and then submit the form via Ajax. After removing the validation it works fine, but in place preventDefault doesn't seem to work. $(document).on("keydown", "input[class='p']", functi

jQuery's preventDefault doesn't work with generated forms

Signal I am trying to generate a form by clicking on a list of users and post the data using AJAX. The preventDefaultelement does not work. I want to validate the form using AJAX without reloading the page. my code: $(function(){ $("#members_list ul > li")

jQuery event.PreventDefault doesn't work in user defined function

Mickey I am creating a function that will receive a URL and then display that URL in a lightbox. I'm having trouble with event.preventDefault() in a function, it says it's not a function in the error console. I've tried passing the event to the function explic

jQuery .click() event.preventDefault() doesn't work

Richard King: I'm building an extensible web application by putting scripts into a preset directory. The script needs to read the file header before going to the page, so I need to use .preventDefault() when I click the link and run some JScript first. Unfortu

jQuery preventDefault doesn't work after field validation

Jules The following code is designed to validate that the input is not Blankt and then submit the form via Ajax. After removing the validation it works fine, but in place preventDefault doesn't seem to work. $(document).on("keydown", "input[class='p']", functi

jQuery UI tab beforeLoad preventDefault doesn't work

Judge God Somehow the e.preventDefault()on beforeLoad()event in jQuery UI Tabs is not working properly. Here is a small example: <div id="tabs"> <ul> <li><a href="#exampleExistingTab">Existing Tab</a></li> <li><a href="/path/to/remote/tab">

jQuery event.PreventDefault doesn't work in user defined function

Mickey I am creating a function that will receive a URL and then display that URL in a lightbox. I'm having trouble with event.preventDefault() in a function, it says it's not a function in the error console. I've tried passing the event to the function explic

preventDefault doesn't work in Firefox

Andrew Burrow I have an input called shop_cat_edit and the code below. But in FireFox this code never works...even IE accepts it. What am I doing wrong? $('[name=shop_cat_edit]').on('click',function(e){ $('#shop_cat_selector_form').on('submit', function(){e

PreventDefault doesn't work with delegates

Mika H. I'm trying to write some JQuery so that whenever the user clicks on a link (ie, a amarker), an alert appears and the link doesn't actually jump to another place. $(document).ready(function() { $(document.body).on('click',"a",function(event){

PreventDefault doesn't work with delegates

Mika H. I'm trying to write some JQuery so that whenever the user clicks on a link (ie, a amarker), an alert appears and the link doesn't actually jump to another place. $(document).ready(function() { $(document.body).on('click',"a",function(event){

PreventDefault doesn't work with delegates

Mika H. I'm trying to write some JQuery so that whenever the user clicks on a link (ie, a amarker), an alert appears and the link doesn't actually jump to another place. $(document).ready(function() { $(document.body).on('click',"a",function(event){