Question

[Solved] Page reloads on hide/show button click using jQuery

I’m using jQuery to show/hide a div by clicking on the show/hide buttons. However, my code doesn’t work because every time it returns to the way it was before when I click on my buttons. I’m almost sure that this is due to a page reload, because every time I click on a button it reloads the page.
Does anybody know what could be the reason behind this?

Here is the important chunk of code:

<form role="form" method="post" action="./something.php">
  ...
  <button id="hidemultmachines" onclick="$('#multmachines').hide(); $(this).hide(); $('#showmultmachines').show();">
    Hide section below ...
  </button>
  <button id="showmultmachines" onclick="$('#multmachines').show(); $(this).hide(); $('#hidemultmachines').show();">
    ... Create multiple entries
  </button>
  <div id="multmachines">
    ...
  </div>
  <div>
    <div>
      <input type="hidden" name="total" value="{ $smarty.section.i.total }">
      <button type="submit" name="Submit" value="Save">Save</button>
    </div>
  </div>
</form>

And this is my jQuery code in the header:

$(document).ready(function(){
    $('#hidemultmachines').hide();
    $('#multmachines').hide();
}

When I put the buttons outside the form it works. Why?

Enquirer: Othmane

||

Solution #1:

That’s because your button elements have no type specified, and by default button elements have their type set to “submit”. When you click one of the buttons, they attempt to submit your form. Simply specifying a type of “button” will fix this:

<button type="button" class="close" id="hidemultmachines" onclick="..."></button>
Respondent: James Donnelly

Solution #2:

A couple of things here:

1) It would be best to separate the HTML from the jQuery.
2) The default behavior for a button is to submit a form, which means it will refresh the page if there is no form action. This can be fixed with preventDefault()

To sum this up in code:

HTML

<button class="close" id="hidemultmachines" >Hide section below <img alt="Close" width="35" height="35" src="../images/close.png"> </button>

JS:

$(document).ready(function() {
$("#hidemultmachines").on("click", function(e) {
  e.preventDefault();
  $('#multmachines').hide();    
  $(this).hide();
  $('#showmultmachines').show();
});
});
Respondent: Victoria Ruiz

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy