sutterhome1971
sutterhome1971

Reputation: 400

Hide all elements with class name

I am new to JQuery. There are two HTML elements (P and input). on click of a button, I want to hide those two elements. Both have same class name. The simple code is not working. Any suggestions please.

thanks much nath

<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>Demo</title>
</head>

<body> <a href="http://jquery.com/">jQuery</a>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            $("#hide#").click(function() {
                $(.test).hide();
            });
            $("#show").click(function() {
                $(.test).show();
            });
        });
    </script>
    <p class="test">Hello this is P element that I am trying to hide using its class</p> First name:
    <input class="test1" type="text" name="fname">
    <button id="hide">Hide</button>
    <button id="show">Show</button>
</body>

</html>

Upvotes: 1

Views: 3803

Answers (2)

Vim
Vim

Reputation: 559

$(document).ready(function(){

  $('#hide').on('click', function(){
    $('.test').hide()
    });

   $('#show').on('click', function(){
    $('.test').show()
    });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class='test'>some text1</p>
<p class='test'>some text2</p>

<button type='button' id='hide'>hide</button>
<button type='button' id='show'>show</button>

Upvotes: 3

Orpheus
Orpheus

Reputation: 767

Well, your jQuery is malformed. There's problem #1:

$(document).ready(function(){
  $("#hide").click(function(){ //assuming "hide#" is the button's ID. 
    $('.test').hide();
  });
  $("#show").click(function(){
    $('.test').show();
  });
});

I'd also change the "Hide" button's id to just "hide" if it isn't already, in this instance.

You also forgot to have enclosing single quotes/double quotes to close your selectors, which is why the hide wasn't even working to begin with.

Upvotes: 0

Related Questions