Ok, so i have a form and it has several groups of fields, like a facebook account settings edit, to show when you click it.
<form id="test" action="#" method="POST">
<ul class="items">
<li>
<button class="show-content-button">Show</button>
<div class="form-content ui-helper-hidden">
Hello
</div>
</li>
<li>
<button class="show-content-button">Show</button>
<div class="form-content ui-helper-hidden">
Hello
</div>
</li>
<li>
<button class="show-content-button">Show</button>
<div class="form-content ui-helper-hidden">
Hello
</div>
</li>
</ul>
</form>
<script type="text/javascript">
$(function() {
$("form#test").submit(function() {
alert("hello i have been submitted");
})
$(".show-content-button").click(function() {
var $button = $(this);
if ($button.text() === "Show") {
$(".form-content", $button.parent()).fadeIn(400);
$button.html("Hide");
} else if ($button.text() === "Hide") {
$(".form-content", $button.parent()).fadeOut(200);
$button.html("Show");
}
})
})
</script>
When i click one of the shows, it causes the form to be submitted… why? I can fix this problem by returning false on the button click event, BUT, i feel that this is a hack and not a solution. Anyone help?
I believe the problem is that by default (in browsers other than IE) the
typeof the button issubmit– for your use case, you want it to bebutton. Adding an attributetype="button", should fix it.Here’s a working example showing the effect of [the lack of] the
typeattribute for<button>s. You’ll have to see the network activity in your browser’s development tool (Firebug in FF, Developer Tools in Chrome)