ILikeTurtles
ILikeTurtles

Reputation: 1022

jquery toggle not functioning

My Jscript/Jquery is not working. I can alert but I cannot get my div to toggle. Can someone explain to me why please? My code is below. I am using JSP if it matters.

My Javascript

$(window).ready(function(){
    $(".moreButtonClass").click(function(e){
        var id = this.id;
        var cleanid = id.replace(/[^\d]/g, "");
        var dog = "post" + cleanid;
        alert(dog);
        $(dog).toggle();
    });
});

My Html

<div id="content">
    <h1>Site Update Log:</h1>
<% for(int i = 0; i<2; i++){ %>
    <div class="blogPost" id="postGroup<%= i %>">
        <div>The ID is :<%out.print(indexModel.miniBlogConnector.GetID(i));%></div>
        <div>The DATE is :<%out.print(indexModel.miniBlogConnector.GetDate(i));%></div>
        <div>The AUTHOR is :<%out.print(indexModel.miniBlogConnector.GetAuthor(i));%></div>
        <div>The MINIPOST is :<%out.print(indexModel.miniBlogConnector.GetShortPost(i));%></div>
        <div class="MainPost" id="post<%=i%>">The POST is :<%out.print(indexModel.miniBlogConnector.GetPost(i));%></div>
        <button type="button" class="moreButtonClass" id="moreButton<%=i%>">more</button>
    </div>
<% } %>
</div> <!-- end #content -->

My CSS

.MainPost {
    display:none;
}

Can anyone please explain to me why I can alert dog and get the correct variable name. But when I try to toggle it; it is not functioning. Nothing happens. No errors; no changes. It absolutely does nothing. I even tried using console.log and was unable to get it to react. The button works because the alert works; but the toggle is not functioning.

Can any one let me know how to fix this please?

Upvotes: 0

Views: 71

Answers (3)

PSR
PSR

Reputation: 40318

You missed the selector # here.Then it will consider as a variable not DOM element

var dog = "#post" + cleanid;
        $(dog).toggle();  

or

$("#"+dog).toggle();

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

If the content in the dog is an ID, use this:

$("#" + dog).toggle();

Or, if it is a class, use this:

$("." + dog).toggle();

Since, in your case, it is going to be an ID, you need to use the first one.

Upvotes: 1

karthikr
karthikr

Reputation: 99630

Here dog is just a variable, and not a DOM node.

You need to do:

$("#"+dog).toggle(); //assuming it is an id. if class, use . instead of  #

Upvotes: 1

Related Questions