0

I have this simple wrap, bind to onClick

HTML

<button class="button secondary" onclick="editButton(this)">Edit</button>

JQuery

function editButton(edit) {
var row = $(edit).closest('.row'),
    cells = row.children().toArray(),
    i=0, 
    inputName = "",
    inputValue = "", 
    html = "";

cells.pop(); // remove control cell

for(i; i<cells.length; i++) {
    inputName = $(cells[i]).attr('data-name');
    inputValue = $(cells[i]).attr('data-value');
    html = "<input type='text' name='"+inputName+"' value='"+inputValue+"'>";
    $(cells[i]).html(html);
}

$(row).wrap('<form action="/action_page.php" method="post"></form>');
$(row).wrap('<div class="test"></div>'); //this works! 

}

instead of wrapping the dom, the page refresh to action_page.php

aahhaa
  • 2,240
  • 3
  • 19
  • 30
  • That's because the ` – Terry Jan 07 '19 at 21:46
  • Possible duplicate of [How do I make an HTML button not reload the page](https://stackoverflow.com/questions/1878264/how-do-i-make-an-html-button-not-reload-the-page) – Terry Jan 07 '19 at 21:46

2 Answers2

1

you need to stop the event

<div class="row">
    <div class="col">
        <button class="button secondary" onclick="editButton(event, this)">Edit</button>

    </div>

</div>

<script>
function editButton(e, edit) {
    e.stopPropagation(); e.preventDefault();

    var row = $(edit).closest('.row');
    $(row).wrap( '<form method="post" action="/action_page.php"></form>');
    $(row).wrap('<div class="test"></div>'); //this works!

    console.log( 'done');

}
</script>
David Bray
  • 566
  • 1
  • 3
  • 15
1

I realized I need to declare a button type, without declaration, it defaulted to type=submit;

<button class="button button secondary" onclick="editButton(this)">Edit</button>
aahhaa
  • 2,240
  • 3
  • 19
  • 30
  • 1
    that is a great point aahhaa, including the type="button" attribute negates the need for preventDefault & stopPropagation ... – David Bray Jan 07 '19 at 22:47