Aaron Thomas Aaron Thomas - 7 months ago 24
Javascript Question

.toggle() sometimes taking double click before working

I have a simple application, where I'd like to toggle between showing and hiding elements in a fieldset using jQuery's .toggle effect. The trouble is, occasionally I have to double-click the button that enables the toggle, to get it to work.

Any ideas on what's going on?

HTML:

<!DOCTYPE html>
<html>
<head>
<script src="jquery-2.1.1.min.js"></script>
<script src="test.js"></script>
</head>
<body>
<div class="LeftFrame">
<div id="LeftTable"><strong>Left</div>
</div>
<div id="MainTable"><strong>Main
<div>
<br>
<form><fieldset><legend><button id="buttonShowFields">Add Info</button></legend>
<div id="InfoAddFields">
ID: <input type="text"><br>
Serial Number: <input type="text"><br>
Location: <select id="inputLocation">
<option>Location1</option>
<option>Location2</option></select><br>
Status: <select id="inputStatus">
<option>Complete</option>
<option>In Process</option></select><br>
</div>
</fieldset></form>
</div>
</div>
</body>
</html>


... and javascript (test.js ref in html above):

$(document).ready(function(){
// Show options to add workorder
// $("#WOAddFields").hide();
$("#buttonShowFields").click(function(){
$("#InfoAddFields").toggle();
});

});

Answer

Prevent the submit with event.preventDefault() when you click the button

http://jsfiddle.net/3NPPP/

$(document).ready(function(){
    $("#buttonShowFields").click(function(e){
       e.preventDefault();
       $("#InfoAddFields").toggle();
    });

});