simplesam
simplesam

Reputation: 61

How do I use JQuery to return the value of the button clicked?

I want to store the value selected from a dropdown menu to run a query in the database to render the subsequent page.

How do I return only one of the values that's clicked from the dropdown menu?

The dropdown menu is created from the database:

            <div class="dropdown-content" id="account">
                <% for(var i=0; i < parentAccounts.rows.length; i++){ %>
                    <a href="/layout" >
                        <%- parentAccounts.rows[i].parent_account %>
                    </a>
                <% } %>
            </div>

The jquery script will return all the names:

        <script>
            $("#account").click(function(){
                var parent_account = ($(this).text());
                alert(parent_account);
            });
        </script>

There are only two unique items in the table at the moment.

Upvotes: 1

Views: 39

Answers (2)

Molda
Molda

Reputation: 5704

Assuming the rendered html looks like this:

<div class="dropdown-content" id="account">
    <a href="/layout">1</a>
    <a href="/layout2">2</a>
</div>

In your code you handle a click on the div and not on the a element.

So all you need is this:

$("#account > a").click(function(e){
     var $a = $(this);
    // $a is the "a element"
    alert($a.text());
    
    // to prevent browser going to the link in href call 
    e.preventDefault();    
});

Upvotes: 2

simplesam
simplesam

Reputation: 61

            <div class="dropdown-content" id="account">
                <% for(var i=0; i < parentAccounts.rows.length; i++){ %>
                    <a href="/layout" >
                        <%- parentAccounts.rows[i].parent_account %>
                    </a>
                <% } %>
            </div>
            $("#account > a").click(function(){
                var parent_account = ($(this).text());
                alert(parent_account);
            });

Upvotes: 0

Related Questions