简体   繁体   中英

conditionally disable a link_to

In my Rails app, I want to enable people to delete projects only once they've entered in the title of the project:

在此处输入图片说明

My current "Delete Button" link is defined as follows:

   <%= link_to "Delete Project", @project, :method=> :delete, :class=>"btn btn-danger disabled delete_project_btn"%>

Why the styling works correctly, the user can still click the link even when the button has the disabled class.

I'd like to only be able to delete the project when the user has added the name of the project:

$('.delete_project_btn').click(function(e){
    if($(this).hasClass('disabled')){
      console.log('preventing link click');
      e.preventDefault();
    }else{

    }
  });

    $('.delete_project_text_area').blur(function(){
      if($(this).val() == <%=@project.title%>){
        $('.delete_project_btn').removeClass('disabled');
      }else{
        if(!$('.delete_project_btn').hasClass('disabled')){
          $('.delete_project_btn').addClass('disabled');  
        }
      }
    });

I am able to see the log message "preventing link click" when I click the "Delete Project" button without having entered the name of the project, but it is still deleting the project.

How can I conditionally disable a link_to?

I ended up removing the original link_to and replacing it with a dummy button, only adding the link once the user has typed the full title of the project:

  <div class="modal-footer">
    <button type="button" class="btn btn-cancel" data-dismiss="modal" aria-hidden="true">Cancel</button>
    <button class="btn btn-danger delete_project_btn disabled">Delete Project</button>
  </div>
</div>

<script type="text/javascript">

    $('.delete_project_text_area').bind('input propertychange', function(){
      if($(this).val() == "<%=@project.title%>"){
        $('.delete_project_btn').replaceWith('<%=link_to "Delete Project", @project, :method=> :delete, :class=>"btn btn-danger delete_project_btn"%>');
      }else{
        if(!$('.delete_project_btn').hasClass('disabled')){
          $('.delete_project_btn').replaceWith('<button class="btn btn-danger delete_project_btn disabled">Delete Project</button>');
        }
      }
    });
</script>

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