mikeyc24
mikeyc24

Reputation: 53

displaying hidden html via a button with javascript

I am having trouble showing a hidden div field on my rails app. Below is the code:

  # application.js file 
  $(document).ready(function() {
    $(document).on("click", "button.click-c", function() {
      $("div.refresh").show();
      console.log("is this going to console")
      //$("div.refresh").toggle();
      //alert("test");
    });
  });

View page:

<button type="button" class="click-c" onclick="click">click</button>
<div id="refresh" class="hidden" >
  <p> hidden content line <%= display info %> </p>
</div>

Also for applciation.css I have:

 .hidden { display: none; }

For the JS code, I tried both .toggle and .show. The button is working on alert("test") and is also printing to the console. Why is it that when the button is clicked, it will not display the hidden lines?

Upvotes: 0

Views: 32

Answers (2)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

As @Pavan said you have to change class. to id# [Pavan's answer is the correct answer if you have one button and one refresh.hidden element].. But if you have multiple buttons and hidden elements

Id must be unique so don't duplicate ids .. see the next demo

//# application.js file 
$(document).ready(function() {
  $(document).on("click", "button.click-c", function() {
    $("div.hidden").not($(this).next('div.hidden')).hide();
    console.log("is this going to console")
    $(this).next('div.hidden').slideToggle();
    //alert("test");
  });
});
.click-c{
  display: block;
}
.hidden { 
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="click-c">click</button>
  <div id="refresh1" class="hidden">
  <p> hidden content line <%= display info %> </p>
</div>
<button type="button" class="click-c">click</button>
  <div id="refresh2" class="hidden">
  <p> hidden content line <%= display info %> </p>
</div>
<button type="button" class="click-c">click</button>
  <div id="refresh3" class="hidden">
  <p> hidden content line <%= display info %> </p>
</div>

Upvotes: 0

Pavan
Pavan

Reputation: 33542

You have defined the div with id as refresh but you are using it as class name in JS code

$("div.refresh").show();

Should be

$("div#refresh").show();

Upvotes: 2

Related Questions