Showing the chosen value using JavaScript

Using the Bootstrap btn-group to select a single value, how can I display the selected value? Here is an example of my code:

<div class="input-group">
    <div id="radioBtn" class="btn-group">
        <a class="btn btn-primary btn-sm active" data-toggle="fun" data-title="Y">YES</a>
        <a class="btn btn-primary btn-sm notActive" data-toggle="fun" data-title="X">I don't know</a>
        <a class="btn btn-primary btn-sm notActive" data-toggle="fun" data-title="N">NO</a>
    </div>
    <input type="hidden" name="fun" id="fun">
</div>

And here is the corresponding JavaScript:

$('#radioBtn a').on('click', function(){
  var selected = $(this).data('title');
  var toggle = $(this).data('toggle');
  $('#'+toggle).prop('value', selected);

 $('a[data-toggle="'+toggle+'"]').not('[data-title="'+selected+'"]').removeClass('active').addClass('notActive');
 $('a[data-toggle="'+toggle+'"][data-title="'+selected+'"]').removeClass('notActive').addClass('active');
})

Answer №1

  1. Clean up your code by eliminating the spaces in your data- title attribute in both the HTML and JS, as these are causing errors.
  2. Insert a
    <div id="display"></div>
    somewhere in your HTML and customize its style to your liking.
  3. Include this line in your JavaScript click handler: $('#display').html(sel);

Check out a demo here.

If you would rather display the text of the radio button instead of the value, use

$('#display').html($(this).html());
instead of step 3.

Task completed.

Answer №2

If you're looking to retrieve the value or text from a clicked button in a button group, here's an example of how I achieve this:

HTML

  <div id="aBtnGroup" class="btn-group">
    <button type="button" value="A" class="btn btn-default">Option A</button>
    <button type="button" value="B" class="btn btn-default">Option B</button>
    <button type="button" value="C" class="btn btn-default">Option C</button>
  </div>
  <p>
  <div>Selected Value:  <span id="selectedValue"></span></div>

JS

$(document).ready(function() {

  // Capture click event, store button in variable, and retrieve values from that variable
  $('#aBtnGroup button').on('click', function() {
    var selectedBtn = $(this);

    selectedBtn.addClass('active').siblings().removeClass('active');
    var buttonText = selectedBtn.text();
    var buttonValue = selectedBtn.val();
    console.log(buttonText + ' - ' + buttonValue);

    $('#selectedValue').text(buttonValue);
  });

  // Use this to set default value upon document load
  // It will trigger the above click event to update accordingly
  $('#aBtnGroup button[value="B"]').click();
});

CONSOLE OUTPUT

Option A - A
Option B - B
Option C - C 

I hope this explanation is helpful!

Sample Link

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

Error: Variable 'err' is undefined in Node.js

Why am I getting a ReferenceError: err is not defined even though it is supposed to be defined here? const sampleObject = require('./sampleObject'); const sampleModel = (callback) => { if (true) { sampleObject.sampleRetrieval(err ...

Creating a route-guard in a Vue.js/Firebase authentication system for secure navigation

I have created a Vue.js/Firebase authentication interface following a tutorial. The app is mostly functioning properly, but I am experiencing issues with the route guard. Upon signing in and redirecting from "http://localhost:8080/home" to "http://localh ...

"Getting an 'Undefined index' error while accessing a JavaScript variable in PHP

Every row in my table contains an Edit button. I managed to fetch the row number by clicking on the Edit button using JavaScript, but I am unsure how to do it in PHP. My attempt to pass the variable from JS to PHP resulted in an error: Undefined index ...

Troubles with Angular elements not aligning correctly when using the "display: block" property

When using an angular element for a directive with "display: block", it may not automatically take up 100% of the width of the parent container. In order to ensure that it does, the width must be explicitly set to "100%" in the CSS. Despite setting "width: ...

Access a dynamic link through JavaScript after receiving it from an AJAX response

Looking to transition my PHP queries to Ajax for better efficiency. Currently using this snippet in PHP to display song ID results: <a href="javascript:songinfo(<?php echo $currentSong->ID; ?>)" title="Lyrics and song info"></a><? ...

Aligning the text vertically in the center while also rotating it 90 degrees to the right, alongside blocking the image and icon elements

I have been experimenting with Bootstrap Trying to create a layout with an image aligned to the top right, a rotated paragraph with a star symbol, and a vertical arrangement of five star symbols. Here's a screenshot of what I'm aiming for: Scre ...

Arrange the objects in an array using a priority array as a guideline

I need assistance with sorting an array of objects based on a status value from the backend system. The sorting priority should follow a specific order defined in the priority array: const priority = [ "APPROVED", "WITHDRAW_PENDING", "PENDING", "W ...

Sending JavaScript variables to an external CSS file

I've been searching for a solution without much luck. I must admit, my CSS skills are pretty basic. Currently, I am using Muxy.io to manage notifications for my livestreams. The platform allows customization of notifications through HTML and CSS file ...

Include a suffix after the user's input in a Material UI TextField

I need to implement a TextField element that displays the entered value followed by an Input Adornment. Can I have the percentage sign (%) appear after the entered value instead of at the end of the input? Currently, the percentage sign (%) appears at the ...

What is the method for adding <option> tags to a <select> statement using a for loop?

Currently, I am facing a challenge in dynamically populating the <option> tags within a <select> menu. My approach involves using a for loop in JavaScript to cycle through the number of options and append them to the select tag. The part of th ...

Prevent selection, enable copying and pasting

As I develop an application that alters the default selection behavior to allow the copying and pasting of elements, a challenge has arisen. Disabling the ability to select also eliminates copy events. I initially attempted to use the following: onselect ...

"Sorry, but there seems to be an issue with

My shop: { customers: [ { id: 12345, name: Customer A }, { id: 54321, name: Customer B } ] } I am attempting to modify the name attribute for Customer A. I am utilizi ...

Guide on setting up and duplicating a template in Vue.js

Allow the user to create multiple person entries by clicking a button with the method "useIt()". A template has been created for this purpose. When the button is clicked, the template should be duplicated and added to the container div. This functionality ...

Mongoose failing to persist subdocument

After trying to insert into my collection, I noticed that the sub-document is not being saved along with it. This issue has left me puzzled. This is the scheme/model I am working with: import { Schema, Document, Model, model } from 'mongoose' ...

Troubleshooting: Issues with jQuery's add/removeClass function and AJAX functionality

Currently, I am utilizing Isotope along with AJAX to fetch some WordPress posts. Everything seems to be functioning correctly, except that the default Isotope animation runs when new content is loaded via AJAX, which appears somewhat awkward. Although, I s ...

Enable hyperlink to open in a new browser tab after user clicks on button embedded inside an iFrame

<head> </head> <div> <iframe src="https://....."></iframe> </div> https://i.sstatic.net/dk21i.png I'm looking for a way to open the link in a new tab when clicking on this button. Currently, the page loads wi ...

Tips for updating a specific portion of a component in react.js

import React,{useEffect} from 'react'; import CloudTables from '@cloudtables/react'; import { useState } from 'react'; function DataGridTable ({ input1Value, input2Value }) { return ( <div className="con ...

javascript utilize function parameters to pass control names

Is there a way to pass control IDs from code behind to HTML without knowing the control names in advance due to dynamic generation? The regular method using MyTextBox = document.getElementById("<%= TextBox1.ClientID %>"); won't work in this scen ...

Retrieve the content of all textareas in a specific order that can be

Is there a way to collect all the textareas in a sortable order and then insert them into another textarea? Option 1: Use $("div textarea").val(); Option 2: Make use of $("div textarea").text(); The Issue: Option 1: Value gets updated with new input bu ...

Tips for Embedding External JavaScript and URLs in Joomla Protostar Template

I'm interested in incorporating a hamburger menu into my Joomla protostar template, similar to the one featured on this URL: ['https://codepen.io/PaulVanO/pen/GgGeyE'] This will provide me with a fullscreen hamburger menu for both desktop ...