Question

I have a following problem:

Inside a form for a new project on projects/new page there is a checkbox which is resposible for toggling is_public attribute of project. I would like to provide user a pop-up javascript confirmation window before creating new project but only if this particular checkbox is checked.

So far I've been trying to do it like this:

<%= labelled_form_for @project do |f| %>
...
<%= f.check_box :is_public %>
...
<%= submit_tag 'create', :confirm => params[:project][:is_public] == '1' ? "Are you sure you want to create public project?" : nil  %>

But because create action is not executed until this moment, params[:project][:is_public] do not exist and thus this solution does not work.

I've been thinking about using jquery to find out whether this checkbox is checked, but I don't know how I would pass obtained jquery variable to rails.

Edit

Here's the final implementation.

$(function(){
  $('#new_project').on('submit.confirm', function(){
    if ($('#project_is_public').prop( "checked" )) {
      if(!confirm("Are you sure you want to create this project as public?")){
        $(this).removeAttr('data-submitted');
        return false;
      }
    }
    return true;
  });
});

submitted data attribute (which was kind of preventing multiple form submissions) blocked the possibility of submitting the form again after clicking on cancel button for the first time.

Était-ce utile?

La solution

You can confirm in form submit ..

for this you need to validate using jquery form submit for example

$(document).ready(function(){
$('#form_id').submit(function(){
   if($('#my_check_box_id').is(":checked")) {
     message = confirm("Are you sure to make this project public?");
      if(message) {
        return true;
      } else {
       return false;
      }
   } else {
     return true;
   }
});
});

Hope this will help you :)

Edit

$(document).ready(function(){
    $('#form_id').submit(function(){
       if($('#my_check_box_id').prop( "checked" )) {
         message = confirm("Are you sure to make this project public?");
          if(message) {
            return true;
          } else {
           return false;
          }
       } else {
         return true;
       }
    });
    });
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top