Wednesday, January 16, 2013

HTML button: submit or not submit a form?



 In a lot of cases, we only want buttons to play JavaScript function, but not submit a form.
For example (button submitting  form):
<form name="enrollment_manager_listed" method="post" action="submit.php" >
  <button   id="filter"  onclick="test()"> Click me </button>
 <input type="submit" name="submit_em" value="Submit" /> 
 <select  name="users-out" id="students-out"  multiple="multiple" size="10">
                <option value="4" title="Mr. Student Account">Mr. Student Account</option>
                 <option value="28" title="Mr JJ DD">Mr JJ DD</option>
                 <option value="32" title="Dr Jack Doe">Dr Jack Doe</option>
                  <option value="26" title="Dr Jack Doe1">Dr Jack Doe1</option>
                  <option value="30" title="Dr Jane Doe2">Dr Jane Doe2</option> 
                  </select>
</form>
 <script type="text/javascript">
   function test(){
   from_s = document.getElementById('students-out');
   var temp  = from_s.options[from_s.options.length-1];
   from_s.add(temp, from_s.options[0]);
   }
 </script>
In this script, when the "Click me" button is clicked, the bottom of  option is moved to the top and the form is submitted. But I only want to  keep moving the items in options  using  button "Click me" without submitting the form. The form  submission is only controlled by "submit" button.
 To do this, add type="button"  in button in order to not submit a form. i.e change
 <button   id="filter"  onclick="test()"> Click me </button>
to 
<button  type='button' id="filter"  onclick="test()"> Click me </button>

No comments:

Post a Comment