Prince Prince - 4 months ago 9
Javascript Question

Hide all the elements with a class using jquery

I am new to javascript and really enjoying it but I am now facing a problem which is a bit confusing to me.

I wrote the code below to hide all the element with a class

male
, but It does not work. When I replace the class
male
by an
id
the code start working.



<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form class="form-register" method="post" action="">

<div class="form-title-row">
<h1>Create an account</h1>
</div>

<div class="form-row">
<label>
<span>Gender</span>
<select name="register_as" id="dropdown">
<option value="none">Select One</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</label>
</div>

<div class="form-row" class="male">
<label>
<span>First Name</span>
<input type="text" name="firstname">
</label>
</div>

<div class="form-row" class="male">
<label>
<span>Last Name</span>
<input type="text" name="lastname">
</label>
</div>

<div class="form-row">
<label>
<span>Email</span>
<input type="email" name="email">
</label>
</div>

<div class="form-row">
<button type="submit">Register</button>
</div>

<script>
$(document).ready(function(){
$(".male").hide();
$("#dropdown").change(function(){
if ($("#dropdown").val() == "male") {
$(".male").show();
} else {
$(".male").hide();
}
});
});
</script>
</form>





I do not really know how to solve this problem. Kindly help me.

Answer

It's because you have double class attribute for elements meaning only first class will take effect and leading to no elements with class .male

You can list multiple classes using space inside same class attribute:

<div class="form-row male">

Optimized JS code

You can use .toggle(true/false) to tell if element must be hidden or shown.

Also I suggest add css for .male: .male {display: none;} to prevent element from being displayed while JS is still processed.

$(document).ready(function(){
    $(".male").hide();

    $("#dropdown").change(function(){
        $(".male").toggle($("#dropdown").val() == "male");
    });
});
Comments