Ad

Display The Selected/active Link In A Div Using JQuery

- 1 answer

I have a simple html menu, when a menu item is clicked a class of `mg_cats_selected" is added to the anchor tag (which is the menu item).

I would like to copy the text value of the active/selected anchor tag and display it in another div on the page, but I would like to only display it once. When a new item link is clicked, I want to remove the old value from the separate div that I've created it and display the new value of the new selected menu item.

I hope that makes sense.

This is the HTML menu

<div id="mgf_165" class="mg_filter mg_new_filters">

    <a rel="163" id="163" class="mgf_id_163 mgf mg_cats_selected left_menu" target="_blank" rel="nofollow noreferrer" href="javascript:void(0)">Bathrooms Sinks</a>

    <a id="164" rel="164" class="mgf_id_164  mgf  left_menu" target="_blank" rel="nofollow noreferrer" href="javascript:void(0)">Bowed</a>

</div>

This is the jQuery and the div where I wanna display the text values.

<script type="text/javascript">
jQuery(document).ready(function(){
    console.log('test');
    jQuery("a.left_menu").click(function(){
         var txt = jQuery("a.left_menu").text();
         //$(this).attr('rel');
         jQuery("#category").append(txt);
    });
});
</script>

<div id="category">
</div>

At the moment when I click on, say, "Bowed", this displays in the div

Bathrooms SinksBowed

Alt;/div>

At the moment when I click on, say, "Bowed", this displays in the div

Bathrooms SinksBowed

And if I click again on "Bathroom Sinks", the same thing repeats

Bathrooms SinksBowedBathrooms SinksBowed

How can I deal with that? And did I follow the correct logic here?

Ad

Answer

You are currently getting the text of all the menu items and then appending it to the div.

You need to get the text of the clicked menu item, and then set the content of the div to the text value of that menu item.

jQuery(this)     // the clicked menu item
jQuery('#category').text('VALUE')   // set the text content of the tag to VALUE

Working solution on JSFiddle..

See Inside the Event Handling Function to learn more about jQuery event handling.

Ad
source: stackoverflow.com
Ad