submiting form on div click with js

2019-09-05 13:49发布

I have a div element and I want that when I click on it i submit a form which is hidden.

div code

<div class="a15 training-exercise">
    some text
    <form accept-charset="UTF-8" action="/trainings/1/training_exercises/5" data-remote="true" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓"><input name="_method" type="hidden" value="put"></div>  
        <input id="training_exercise_done" name="training_exercise[done]" type="text" value="false">
        <input name="commit" type="submit" value="subit">
    </form>
</div>

coffescript

$ ->
    $('.training-exercise').click ->
        if $(this).hasClass('done')
            $(this).removeClass('done')
            $(this).find('input:text').val(false)
            $(this).closest("form").submit()
        else
            $(this).addClass('done')
            $(this).find('input:text').val(true)
            $(this).closest('form').submit()

corresponding JS code

$(function() {
  return $('.training-exercise').click(function() {
    if ($(this).hasClass('done')) {
      $(this).removeClass('done');
      $(this).find('input:text').val(false);
      return $(this).closest("form").submit;
    } else {
      $(this).addClass('done');
      $(this).find('input:text').val(true);
      return $(this).closest('form').submit;
    }
  });
});

i didn't put checkbox for true and false because f.checkbox gave me some strange results

The problem here is:

1) Everything is happening except form submitting

2) form has visibility: hidden; and it is hidden, but there is empty space where the form is, I want that it looks like there is nothing there

2条回答
放荡不羁爱自由
2楼-- · 2019-09-05 14:24

For 1st problem, try

$(function() {
  $('.training-exercise').click(function() {
      var element = $(this);
         if (element.hasClass('done')) {
         element.removeClass('done');
         element.find('input:text').val(false);
         element.closest('form').submit(); //<-- brackets here.
      } else {
         element.addClass('done');
         element.find('input:text').val(true);
         element.closest('form').submit();
      }
   });
});

For 2nd problem use display:none; instead of visibility:hidden.

查看更多
beautiful°
3楼-- · 2019-09-05 14:29

It seems that form selecting didn't work (although it work when I tried from console)

The solution that works is:

$(this).find('input:submit').submit()
查看更多
登录 后发表回答