6

I have a simple checkbox, generated with:

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

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

3 Answers 3

4

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)

Sign up to request clarification or add additional context in comments.

1 Comment

If this code should work, the checkbox has to be right beneath the form. Use: $(this).parents('form:first').submit(); instead.
2

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();" });

1 Comment

This is close, the actual syntax is document.forms[0].submit()
0

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

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.