Jan 22

Auto Submitting Checkboxes

Assume you have a couple of lists of checkboxes. generally at the end of the lists you would have a submit button to then post the data. but assume you have something like a search from. general web design suggests that things should be done with the minimum number of clicks1

The three-click rule or three click rule is an unofficial web design rule concerning the design of website navigation. It suggests that a user of a website should be able to find any information with no more than three mouse clicks. It is based on the belief that users of a site will become frustrated and often leave if they cannot find the information within the three clicks.

Source: Wikipedia – Three-click rule

so to follow this you would want these checkboxes to filter results without having to hit search every time. well with jQuery you can just bind a forms submit event to the checkboxes

$('#form input[type="checkbox"]').click(function(){

The above code assumes #form is the id to your <form> element but as long as the jQuery returns only one HTML Element which is that form you are submitting it can be anything (meaning you don’t even have to have the checkboxes in the same form if you want). now keep in mind that the moment you click on the checkbox so that it becomes ticked or unticked the from will submit. this also include any textboxes you may have in the form.

Now some people add a bit of extra validating on their receiving page by checking for the value of the submit button. the problem with the code above is that since we aren’t using the submit button any more this value wont be posted to the next page. to post this data too we need to add a little more to our original code.

$('#form input[type="checkbox"]').click(function(){
	input = $("<input>").attr("type", "hidden").attr("name", "mySubmit").val("Submit");

as you can see we create a new hidden input value, make it a hidden input type and give it the same name and value as what our submit button would be. then before we use submit() we call append() which appends the value passed to the function inside the HTML we have selected with jQuery. (so with our form we addend our new HTML to the last bit of HTML before </form>)

this can also work with radio buttons in which case you would replace type="checkbox" with type="radio"

1: generally this isn’t true but i keep hearing it as the first thing to learn with web design courses

Leave a Reply

Your email address will not be published.