tags:

views:

176

answers:

3

I have a simple checkbox, generated with:

<%= Html.CheckBox("myCB" )%>

How can I add an onChange handler to this that does a submit?

+2  A: 

Add an onClick handler to the CheckBox that submits the form the CheckBox belongs to...quick, clickHandler codeless example:

<%= Html.CheckBox("myCB", 
    new { onClick = "$(this).parent('form:first').submit();" });

(example definitely not checked for accuracy)

Justin Niessner
but works fine :)
chris
+2  A: 

If you have only one form, and are not using JQuery (you should be, by the way) try this:

<%= Html.CheckBox("myCB", 
new { onClick = "document.form.submit();" });
Josh Pearce
This is close, the actual syntax is document.forms[0].submit()
chris
A: 

I would highly recommend using jQuery to support this because it makes it easier to add the behavior to a checkbox throughout your site by having the selector either be ID or class-based. Then you could put the script anywhere on the page or in an external .js file.

<script language="javascript" type="text/javascript">
  $('#myCB').click(function() { $(this).parent('form:first').submit(); });
</script>

Alternatively, the selector could be class-based (or any attribute for that matter). More info here: http://docs.jquery.com/Selectors

mkedobbs
I'll probably end up using this on other projects, but for now it's just one place - thanks, though.
chris