Shawn Wilson Shawn Wilson - 2 months ago 11
Javascript Question

Rails 4 Button to confirm and once clicked it shows the proceed button

I am building a rails 5 app with Ruby 2.4.0 and Bootstrap 4 Alpha 6.

What I am trying to do is have 2 buttons, one is invisible when the page loads and the other appears when the primary button is clicked. Once the primary button is clicked it dissapears and the secondary button takes its place on the screen.

My initial button is:

<%= link_to "Confirm your Device", "#", class => "btn btn-warning, :id => "confirm" %>


The button that will replace it is:

<%= link_to "Proceed to Carrier Selection", manufacturer_device_path(@manufacturer, device_div), :class => 'btn btn-outline-primary proceedButton', :id => "proceed" %>


I am a bit stuck on how to achieve this with JavaScript or jQuery.

Any assistance with thit would be greatly appreciated!

Answer

Put your buttons (link_to) inside a div (to make sure they appear on the same place every time) and hide the second one (i.e. id="proceed") using a custom class (e.g. hide), like this:

<style>
  .hide {
    display: none !important;
  }
</style>

<div>
  <%= link_to "Confirm your Device", "#", class: "btn btn-warning", :id => "confirm" %>
  <%= link_to "Proceed to Carrier Selection", manufacturer_device_path(@manufacturer, device_div), class: 'btn btn-outline-primary proceedButton hidden', :id => "proceed" %> 
</div>

This will show the first button and hide the second one when the page is loaded; now you can use jQuery methods addClass() and removeClass() to hide the first button and show the second:

<script type="text/javascript">
  $(document).ready(function() {
    $('#confirm').on('click', function(event) {
      event.preventDefault();
      $(this).addClass('hide');
      $('#proceed').removeClass('hide');
    });
  });
</script>

The above script hides the clicked button (by adding the hide class) and shows the one that was hidden initially (by removing the hide class).

Check this snippet (with generated html from the above code):

$(document).ready(function() {
  $('#confirm').on('click', function(event) {
    event.preventDefault();
    $(this).addClass('hide');
    $('#proceed').removeClass('hide');
  });
});
.hide {
  display: none !important;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
  <a class="btn btn-warning" id="confirm" href="#">Confirm your Device</a>
  <a class="btn btn-outline-primary proceedButton hide" id="proceed" href="#">Proceed to Carrier Selection</a> 
</div>

Note

The original answer used show() and hide() methods (instead of addClass() and removeClass()) but didn't worked when paired with boostrap.