简体   繁体   中英

Submit checkbox state without a submit button

I have a view with a few checkboxes that can be selected or unselected. I'd like to always register any change in a checkbox, without the use of a submit button (the user could forget to do it, and it would waste time).

So, is there a way to handle this inside the view? Up to now, I've only used the controller to do that job.

So, a piece of code :

  @ModelType MvcApplication.OpportuniteDetails

  @Code
       ViewData("Title")="Details"
  @End Code

  <script type="text/javascript">
  $(function () {
    $(':checkbox').change(function() {
        $.ajax({
            url: '@Url.Action("update")',
            type: 'POST',
            data: { isChecked: $(this).is(':checked') },
            success: function (result) { }
        });
    });
  });
  </script>
  [... Some code here...]
  @Html.Raw("Mail sent?") @Html.CheckBox(Model.Opportunite.Mail)

  <input type="checkbox" name="mail" id="mail" onclick="test()" />

You could use AJAX:

$(function() {
    $(':checkbox').change(function() {
        var form = $(this).closest('form');
        $.ajax({
            url: form.attr('action'),
            type: form.attr('method'),
            data: form.serialize(),
            success: function(result) {

            }
        });
    });
});

In this example we subscribe to the change event of each checkbox. When this event is trigerred we look for the containing form and send its contents to the server using an AJAX request.

And if you only wanted to submit the current checkbox state to the server and not the entire form:

$(function() {
    $(':checkbox').change(function() {
        $.ajax({
            url: '@Url.Action("SomeAction")',
            type: 'POST',
            data: { isChecked: $(this).is(':checked') },
            success: function(result) {

            }
        });
    });
});

where you could have a controller action which will do the necessary processing:

[HttpPost]
public ActionResult SomeAction(bool isChecked)
{
    ...
}

If you don't need or want AJAX and just want to submit the form, this

$(':checkbox').change(function() {
    var form = $(this).closest('form');
    form.get( 0 ).submit();
});

would do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM