Chosen item from the dropdown menu in Bootstrap

I am utilizing Bootstrap in combination with RAILS. My main objective is:

  1. create a dropdown list with Bootstrap styling
  2. show the selected item in <p>, <div>, or <span>

The JavaScript code appears as follows:

$(function(){
    $(".dropdown-menu li a").click(function(){
      $("#chosen").text($(this).text());      
   });
});

Here is the corresponding HTML:

<div class="container">        
  <h2>Choose</h2>
  <div class="dropdown">
    <button class="btn btn-default dropdown-toggle" type="button" id="menu1" data-toggle="dropdown">Templates
    <span class="caret"></span></button>
    <ul class="dropdown-menu" role="menu" aria-labelledby="menu1">
        <% @books.each do |book| %>
            <li role="presentation">
                <a role="menuitem" tabindex="-1" href="#">
                    <%= book.name %>
                </a>
            </li>
        <% end %>              
    </ul>
  </div>      
  <p id="chosen"></p>      
</div>

The issue I am facing is that once an option is selected, the text displayed in <p id="chosen"> only appears briefly before disappearing.

Answer №1

Here's a suggestion for your HTML layout:

<div class="wrapper">        
  <h2>Make a selection</h2>
  <div class="dropdown-menu-container">
    <button class="btn btn-default dropdown-toggle" type="button" id="menu1" data-toggle="dropdown">Templates
    <span class="caret"></span></button>
    <ul class="dropdown-menu" role="menu" aria-labelledby="menu1">
        <% @books.each do |book| %>
            <li role="presentation">
                <a role="menuitem" tabindex="-1" href="javascript:void();">
                    <%= book.name %>
                </a>
            </li>
        <% end %>              
    </ul>
  </div>      
  <p id="selected-item"></p>      
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a more concise method to reference the parent scope in AngularJS in this scenario?

Is there a shorter way to reference the parent scope within this controller? $scope.tables = []; $scope.newTable = function(){ $scope.tables.push({name:"Table " + ($scope.tables.length+1),cols:[]}); $scope.selected = $scope.tables.length-1; }; I ...

Display Highcharts in an HTML table format

As I work on developing a system that generates various types of graphs, my goal is to synchronize a chart and table so that when the chart is DRILLDOWNED, the table will also update. Is there a method to convert the data currently displayed by HighChart ...

Verify whether a group of div elements overlaps a fixed div while scrolling

I have a layout with a list of posts and a logo positioned at the bottom of the page. The issue I am facing is that sometimes the title of the posts and the logo overlap, and I want to set the logo's opacity to 0.25 only when the text from .cat-date i ...

Difficulty in extracting data from child elements of JSON documents

Below is the JSON String: "book_types": { "type": "1", "books": [ { "name": "default", "cover": null, "lastUpdated": { "microsecond": 114250, "ctime": "Fri Aug 9 01:27:45 ...

Can you pinpoint the origin of the circular reference that triggers the error when using JSON.stringify?

I am encountering an issue where passing an object to JSON.stringify is resulting in the error "Converting circular structure to JSON," but I cannot pinpoint the exact reason for this. The object is being passed via server-side node.js. app.get('/&a ...

Prevent rapid flashing by adding a delay to the spinner in the jQuery Validations plugin

I'm currently utilizing the jQuery validation plugin available at http://docs.jquery.com/Plugins/validation for implementing client-side validations. For a remote validation to verify the availability of a username in the database, I intend to prolon ...

Adjusting the image to fit the container based on its shorter side, regardless of the image's orientation

I have a square container with a predetermined size. I want to place an image inside the container so that its smaller side fits perfectly with the parent container, while the larger side extends beyond the edges of the container without distorting the ima ...

Integrating individual script into HTML

Imagine you have a file named public/index.html. Additionally, there is another html file called otherScript, which contains only <script> tags with a script inside. How can you include these scripts into your public/index.html file? You intend to ...

What is the best way to ensure that a canvas created using JavaScript spans 100% of the width?

Working with a canvas element generated by Javascript, see the code snippet below: http://jsfiddle.net/mtvzgnmm/ <div id="circle"></div> <script> $('#circle').circleProgress({ value: 0.75, size: 400, ...

Retrieving Vue data from parent components in a nested getter/setter context

<template> <div id="app"> {{ foo.bar }} <button @click="meaning++">click</button> <!--not reactive--> <button @click="foo.bar++">click2</button> </div> </templ ...

When using JavaScript's Date() function, it may sometimes return an

I am currently developing a website that calculates the time elapsed since a specific date. However, when I input the parameters provided by the user and call new Date(), it displays "Invalid Date". This is the code snippet I have been using: http://jsfid ...

Unable to access client's channels cache with empty parameters

In my quest to locate the guild and then channel within that guild, I have employed the following code snippet: const guild = client.guilds.cache.find(guild => guild.name === "bla bla bla"); const channel = guild.channels.cache.find(ch => c ...

Can you explain the varying methods of importing material-ui components and how they differ from each other?

After delving into the documentation for material-ui and exploring various online resources, it appears that there are multiple methods for importing the same component: import TextField from 'material-ui/TextField'; // or import TextField from ...

What is the best way to dynamically load content with AJAX that includes a script?

Currently, I am in the process of developing a website where I am utilizing jquery/ajax to dynamically load content onto the homepage. The test site can be found at [. While the home and about me pages load perfectly, I am encountering an issue with the pr ...

Set the return value of the mongoose function to a variable in node.js

As a newcomer to node js and mongoose, I have encountered the following code in my node js project. I am trying to store the mongoose return record userData in a variable user that is outside of the callback function. var user = null; User.findOne({$and: ...

Move the cursor within the text area upon clicking the button

When the "+header" button is clicked, I am looking to automatically position the insertion point inside the text area. Currently, after pressing the button, the text box displays information like address, date, time etc. but the cursor does not start insid ...

Shared items found in a pair of entities

This function currently returns the difference between two objects, but I need to modify it so that it returns the common objects instead. Any assistance on how to achieve this would be greatly appreciated. Array example: var array1 = [ { "Name": " ...

CSS: Centralizing a Div Element with Fluid Width

I've created a popup that appears in the center of the screen using: transform: translate(-50%, -50%); and position: absolute. However, I'm facing an issue where the width of the popup remains fixed instead of adjusting dynamically based on the c ...

The light/dark mode toggle is a one-time use feature

I've been experimenting with creating a button to toggle between light and dark modes on my website. Initially, it's set to light mode, but when I try switching to dark mode, it works fine. However, the issue arises when attempting to switch back ...

Error encountered while trying to embed SVG file

My method involves utilizing an ajax call to fetch an htm file that constructs an SVG. Although the call retrieves the file successfully, the designated area where it should display only shows: https://i.sstatic.net/8G9IU.jpg Could this issue be related ...