Ways to activate Bootstrap using our javascript

http://getbootstrap.com/javascript/#buttons?

They have provided a demo for radio button toggling in Bootstrap.

I attempted to implement it in my code, but the active state is not switching. What could be causing this issue?

CDNs I am using:

Code input section:

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js">    </script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">        </script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

My script:

$(document).ready(function() {
    $('.btn').button('toggle')
});

My code snippet:

<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio" name="options" id="option" value="a" checked> Option 1 (preselected)
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="options" value="b"> Option 2
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="optionsa" value="c"> Option 3
</label>
</div>

Answer №1

Your JavaScript should be included in the correct order.

Remember that Bootstrap relies on jQuery, so ensure you define it first.

For example: http://jsbin.com/citizeqecupi/1/edit

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

  <script>
    $(document).ready(function() {
      $('.btn').button()
    });

  </script>

</head>
<body>

  <div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio" name="options" id="option" value="a" checked> Option 1 (preselected)
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="options" value="b"> Option 2
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="optionsa" value="c"> Option 3
</label>
</div>

</body>
</html>

Answer №2

It appears that there may be an issue with jQuery in your code.

You can view a sample here.

I have included jQuery version 1.11.0 in the script.

<html>
   <head>
      <meta http-equiv="content-type" content="text/html; charset=UTF-8">
      <title> - jsFiddle demo by iklementiev</title>
      <script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.js"></script>
      <link rel="stylesheet" type="text/css" href="/css/result-light.css">
      <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>        
      <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
      <style type="text/css">        
      </style>
      <script type="text/javascript">
         $(window).load(function(){
         $(document).ready(function() {
             $('.btn').button('toggle')
         });
         });         
      </script>
   </head>
   <body>
      <div class="btn-group" data-toggle="buttons">
         <label class="btn btn-primary">
         <input type="radio" name="options" id="option" value="a" checked=""> Option 1 (preselected)
         </label>
         <label class="btn btn-primary">
         <input type="radio" name="options" id="options" value="b"> Option 2
         </label>
         <label class="btn btn-primary active">
         <input type="radio" name="options" id="optionsa" value="c"> Option 3
         </label>
      </div>
   </body>
</html>

Answer №3

When toggling all of the buttons, the last one will be activated in your situation...

The functionality works even without the toggle parameter. You can see it in action here: http://jsfiddle.net/g2L8ujt7/1/

If you want to programmatically activate the second radio button for example, you can do so by adding a unique class to differentiate it:


...
<label class="btn btn-primary tgl">
     <input type="radio" name="options" id="options" value="b"> Option 2
</label>
... 

In this case, I've added the class tgl to the second radio button

Now you can toggle only this specific button using the following code:

$('.tgl').button('toggle');

For another example, you can check out: http://jsfiddle.net/g2L8ujt7/2/

P.S. If you need to select multiple options, use checkbox buttons instead of radios. Checkboxes allow for multiple choices, while radios are used for selecting only one option from many.

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

Using jQuery, you can add a class to a div by clicking on an element, and then remove that class by clicking away from

I've been looking into this issue and I have found a solution for adding or removing a class to the div that I click on, but not to a separate div altogether. For example, when I click on the input with the class .search-bar, it should add a class to ...

Adding special characters (č,š and ž) to a MySQL database

Recently, I conducted an experiment to see how special characters like č, š, and ž appear in the database once inserted. Interestingly, inserting the string "č_š_ž" resulted in it looking like "Ä_Å¡_ž" in the varchar field of the database. Whil ...

Exploring the wonders of ASP.NET MVC 3 through RESTful routing techniques

As I work on my ASP.NET MVC 3 application, I find myself drawn to the routing standards outlined in a presentation on RESTful best practices at . Even though the examples provided are based on RAILS, I appreciate the clean and natural syntax they offer. A ...

Is it possible to include a border/stroke on a Raphael picture?

Currently, I am attempting to enhance a Raphael image element by adding either a border, stroke, or drop shadow. My end goal is to create an animated glowing border effect. Previously, I successfully implemented this on traditional HTML elements using Java ...

Ways to update or migrate the schema of a remote client's standalone database when performing updates

Situation: Currently, I am developing a desktop-based application that requires management of multiple independent production sites. Each site has its own server, database, and local clients. The software gets automated updates regularly, which includes s ...

The function Waterline.create() is not available

Currently in the process of building a basic REST API using Sails.js and Waterline-ORM, I've encountered an issue regarding Post.create is not a function when trying to create an object within the ORM on a Post request. Here is my model: module.expor ...

Choosing an option in a dropdown menu during ProtractorJS end-to-end testing

I need to automate the selection of an option from a dropdown menu for angular end-to-end tests using protractor. Below is the code snippet for the select option: <select id="locregion" class="create_select ng-pristine ng-invalid ng-invalid-required" ...

Arrange an array by the occurrence rate of its elements within objects contained in another array, using Javascript

I found the explanation to be rather complex. Essentially, my goal is to iterate through each object in the 'objects' array, analyze the 'choice' values, tally the frequency of each letter, and then arrange the original arrays based on ...

Varied elevations dependent on specific screen dimensions

There seems to be a minor issue with the height of the portfolio container divs at specific window widths. The problematic widths range from 1025 to 1041 and from 768 to 784. To visualize this, try resizing your browser window to these dimensions on the fo ...

What methods can be used to determine if a bound function is equal when performing unit testing?

I am looking to verify that when I pass an argument to a function, it is indeed a function reference even though the function reference is passed using the bind() method. Take a look at this shortened code snippet that needs to be tested: initialize: fun ...

Move to the following <article>

I am currently working on developing a JavaScript function that will automatically scroll to the next article whenever the down arrow key is pressed. The challenge I am facing is that my HTML elements are all dynamic and are simply article tags without any ...

What's the best way to test a simple Bearer Strategy implementation in Passport.js using Postman?

Currently, I am diving into the realm of passport authentication specifically how to authenticate a Restful API. I am feeling a bit uncertain about testing what I have. Here is the BearerStrategy code snippet: var BearerStrategy = new Bearer({ }, fun ...

What is the best way to accurately determine the height and offset values of an element while utilizing ng-repeat?

My objective is to determine the offset and height of list items. Once I have those values, I trigger a function in a parent directive. Ultimately, this will involve transitioning elements in and out as they come into view. Issue: Due to the use of ng-rep ...

Passing data between Express controllers using Socket.io

Looking for guidance on using Node.js / Express for my AngularJS backend. I've searched everywhere for help, but can't figure out how to implement the suggestions in my code. Here's how my application functions: A Scala process sends log ...

Invoking a function within an HTML file does not result in triggering an alert message

Hello everyone, thank you for taking the time to look at this. I'm attempting to execute a javascript function when I click on the update button. Here is the javascript code: var text2Array = function() { // This function takes the value from the t ...

Running jQuery code within an AngularJS directive's templateUrl

I am facing an issue where my jQuery code, embedded within an AngularJS directive HTML template, is not functioning as expected. Neither alert("testA"); nor alert("testB"); are being triggered in the provided code snippet. I suspect that the problem lies ...

String passed instead of JSON in Ext JS grid sorting

I encountered an issue while attempting to incorporate server-side sorting with Sencha Ext JS. The JSON paging section appears correct, but the sort property is defined as a String rather than an Array: Actual: {"page":1,"start":0,"limit":50,"sort":"[{&b ...

Duplicate the PHP code for every section found within an INI file

<? $config = parse_ini_file('/list.ini', true); ?> <?echo'<select id="LBox" name="listbox" size="20" style="display:none;">'; foreach($config[MPR] as $id=>$label){ switch ($id) { case ($id== ...

Chat Bot - EmbedMessage

JavaScript is still very new to me and I find the actual code quite challenging to grasp. However, I do have one specific question - how can I display the "cahbResponses" in a MessageEmbed? Despite consulting the Discord JS guides on MessageEmbeds, I' ...

Issue with Angular: Problems with script references

I am currently working on a small Angular app for a school project, and I'm running into an issue where my script is not being imported correctly (it displays '{{1+1}}'). Both the index.html and app.js files are located in the same folder. ...