0

When the button is clicked, 2 sets data is added. I use material design.

Button needs 2 clicks to run function for first time. Due to this, the data is added to table 2 times.

Code

HTML

<button onclick="purchaseList(orderid)" id="dialog">Button</button>

JS

function popup(listid) {

    var starCountRef = firebase.database().ref('Orders/' +
        listid).child('foodItems');
    starCountRef.on('child_added', snapshot => {

        var snaps = snapshot.val();
        var itemPrice = snaps.price;
        var itemName = snaps.productName;
        var itemQuantity = snaps.quantity;

        console.log(itemName);
        $("#producttable").append(
            '<tr><td class="mdl-data-table__cell--non-numeric">' + itemName +
            '</td><td>' + itemQuantity + '</td><td>' + itemPrice + '</td></tr>'
        );
    });

    var dialog = document.querySelector('dialog');
    var showDialogButton = document.querySelector('#dialog');
    if (!dialog.showModal) {
        dialogPolyfill.registerDialog(dialog);
    }
    showDialogButton.addEventListener('click', function() {


        dialog.showModal();

    });
    dialog.querySelector('.close').addEventListener('click', function() {

        var element = document.getElementById("producttable")
        while (element.lastChild) {
            element.removeChild(element.lastChild);
        }
        dialog.close();

    });

}
Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
Ganesh
  • 5
  • 4

3 Answers3

1

This should work:

var element = document.getElementById("producttable")
while (element.lastChild) {
    element.removeChild(element.lastChild);
}

Add this as necessary.

wizzwizz4
  • 6,140
  • 2
  • 26
  • 62
1

I suggest you change your firebase function from using .on to .once to avoid multiple additions of data to your table and as your data isn't expected to change frequently or require active listening you better use .once for performance benefits.

firebase.database().ref('Orders/' + 
    listid + '/foodItems').once('value').then(function(snapshot) {
            // the rest of your code goes here
});
Hamed Baatour
  • 6,664
  • 3
  • 35
  • 47
0

this remocve element with class name ".mdl-data-table__cell--non-numeric" when user click .close

dialog.querySelector('.close').addEventListener('click', function () {

    dialog.close();
         $(".mdl-data-table__cell--non-numeric").remove();
});

UPDATE:

to open dialog on 2nd click use pseudo element to activate like this

<div class=pseudo><button onclick="purchaseList(orderid)"id="dialog" disabled>Button</button></div>
var i=0;
$('.pseudo').click(function(){
 i++;
  if(i==2){
   $("#dialog").prop('disabled',false);
 }
});
jasinth premkumar
  • 1,430
  • 1
  • 12
  • 22