submiting form on div click with js

孤人 提交于 2019-12-13 05:38:53

问题


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


回答1:


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.




回答2:


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()


来源:https://stackoverflow.com/questions/18403112/submiting-form-on-div-click-with-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!