Why won't the text on my toggle button update in my HTML code?

When I use the same id for multiple toggle buttons, the text value is not changing. However, when I use a single button, the text value changes as expected.

The toggle buttons can switch between displaying "am" or "pm."

Below is the JavaScript code I used:

$(document).ready(function(){
  $('#myToggle').on('click', function () {
    var text=$('#myToggle').text();
    if(text === "am"){
      $(this).html('pm');
    } else{
      $(this).text('am');
    }
  });
});

Here is the HTML line used for the toggle button:

<button type="button" data-toggle="collapse" href="#" id="myToggle" class="btn btn-secondary">am</button>

Check out my screenshots https://i.sstatic.net/jVacY.png.

An important note: The id value "myToggle" must be unique.

Answer №1

$(document).ready(function(){
     $('.btn').on('click', function () {
      var text = $(this).text();
      if(text === "am"){
        $(this).html('pm');
      } else{
        $(this).text('am');
     }
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" data-toggle="collapse" href= "#"class="button btn btn-secondary">am</button>

<button type="button" data-toggle="collapse" href= "#" class="button btn btn-secondary">am</button>

It goes against the W3C specification to have multiple elements with the same id in HTML.

jQuery, in this scenario, utilizes the document.getElementById method which only retrieves the first element with that id.

If you require multiple elements, use classes instead.

Answer №2

It is important for ids to be unique within the DOM. To achieve this, classes can be used instead. Simply add a new class to all buttons with similar functionality, such as btn-toggle-time.

Approach 1

HTML:

<button type="button" data-toggle="collapse" href="#" class="btn btn-secondary btn-toggle-time">am</button>

Javascript:

$(document).ready(function(){
  $('.btn-toggle-time').on('click', function (e) {
    e.preventDefault();
    var text = $(this).text();
    if(text === "am"){
      $(this).html('pm');
    } else{
      $(this).text('am');
    }
  });
});

Approach 2

Another option is to style a text field to look like a button. This way, when you submit the form, there's no need to maintain the value through javascript. Run the snippet to see how it works. Instead of changing text, the value of the text field will be modified in this scenario.

$(".input-meridiem").on('click', function(e){
  e.preventDefault();
  var meridiem = $(this).val()
  if(meridiem === 'AM'){
    $(this).val('PM');
  } else {
    $(this).val('AM');
  }
});
input.input-meridiem{
  border: none;
  padding: 10px 20px;
  color: white;
  background: #363239;
  cursor: pointer;
  width: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input value="AM" class="input-meridiem" name="meridiem" readonly/>

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

Implement Offcanvas feature with Bootstrap 3 Navbar set to Fixed Top position

I am in the process of creating a website that will feature a large menu. However, I am not a fan of the collapsed menu that comes with BS3. Instead, I would like to implement a drawer or off-canvas menu similar to the one showcased in BS3's offcanvas ...

Looking to iterate through MongoDB using a promise and a forEach loop? I'm aiming to populate an array

I've been struggling to iterate through elements in my MongoDB database and save the values to an array. Despite putting in hours of effort, I can't seem to get it done. Here's the code snippet: //shopController.js const Product = require ...

how can I trigger an AJAX request after a specific JavaScript function in JSF 2.0

On a regular basis, I utilize a particular method, but I encounter an issue. There is a functionality that involves deleting a certain entity, however, I wish to notify the user who triggers this action with a commandLink by calling a JavaScript function c ...

What is the best way to retrieve text from a span within an input field when it is highlighted?

Is there a way to extract the text from a span that comes before a text input, and when that input is focused, retrieve the span associated with it? Consider this example structure: <div> <label for="id">...</label> <input type="text" ...

What is the correct way to configure dependencies in RequireJS in order to pass variables between files successfully?

I have recently started utilizing requirejs and I am encountering difficulties in establishing connections between these files. Typically, I would just include js files in the correct load order. main.js requirejs.config({ paths: { "j ...

Centering a division inside another division

Hey there, check out my website at . I'm seeking assistance with a specific piece of code. CSS: .pagemenu { padding-top: 25px; padding-right: 2%; padding-left: 2%; text-align: center; } .bubblewrap { display: inline-block; vertical-align: top; ...

How come my XPath is overlooking a condition and choosing several nodes instead?

<flow-end-node _nghost-c50="" id="T000k2d27hnb" class="jtk-draggable jtk-droppable ng-star-inserted jtk-endpoint-anchor jtk-connected xh-highlight" style="top: 160px; left: 592px; z-index: 102;"> <div _ngcontent-c50="" class="invisible-node-holder ...

Using Javascript to create alerts that display all objects

Is there a way to send a single alert with all objects? Whenever I attempt it, I keep getting undefined or [object, object] var array =[]; function object ( name, username, password) this.name = name this.user = username this.pwd = password var obj ...

The variable in Angular stopped working after the addition of a dependent component

Currently, I am working with Angular and have implemented two components. The first component is a navigation bar that includes a search bar. To enable the search functionality in my second component (home), I have added the following code: HTML for the n ...

Optimal method for handling multiple jQuery selectors is to use proper syntax

Is there a preferred industry standard syntax for binding click events to multiple selectors using jQuery? For example: scrollToPoint('.main-nav a, .sub-nav a, .enquire-btn, #showcase-list a, #showcase-more-info a.back-btn') Are there any alter ...

New Issue in Firefox 15: When using divs, content spills over into border images

Before anything else, I want to acknowledge the unprefixing of -moz-border-image in Firefox 15. You can read more about it here: . I made adjustments to my CSS to accommodate Firefox 15. However, I am facing a different issue that needs attention. To ela ...

Can tabs be created without the use of javascript?

I'm currently working on implementing a tabbed box layout, and while I've come across several tutorials that use JavaScript to switch between tabs, I'm wondering if there is a way to achieve the same functionality without relying on JavaScri ...

Delay in the execution of JavaScript code

function appendContent(newContent) { $("#drawer").append(newContent); } function retrieveOuterHtml(element) { return $("<div />").append($(element).clone()).html(); } var allElements = []; $(".pix").each(function() { allElements.push(r ...

What is the best way to create a list and incorporate a sorting function using Vue JS?

Currently working on creating a sort function with Vue js The goal is to initially display a list in ID order by default, and then allow sorting by clicking the asc/desc by name button. Additionally, when the all button is clicked, the list should revert ...

What is the best way to retrieve data from a numerical title in ReactJS?

Currently, I am retrieving information from an excel spreadsheet where the table header is in a numerical format (e.g. 2005-06) like this: https://i.sstatic.net/fLPh7.png Despite my efforts to access the data using objects, I keep encountering an error. ...

Some browsers may not display the table border properly due to issues with border-collapse

There seems to be an issue with the table border displaying inconsistently across different browsers. Take a look at the code snippet below: .test-table, table.test-table th, table.test-table td { border: 1px solid black; border-collapse: collapse; ...

Middleware in Express.js Router

In the following code snippet, I am aiming to limit access to the 'restrictedRoutes' routes without proper authorization. However, I am encountering an issue where 'restrictedRoutes' is affecting all routes except for those within the & ...

AngularJS and adding to an array in the routing process

I'm currently working on creating a contact list with two different views. One view displays all the contacts and includes an option to add a new contact, which is represented by a button rather than a space to input information directly. The other vi ...

Enhance the look of the Tinymce editor in Joomla with personalized formatting options

Is it possible to include a custom format for formatting lists in the TinyMCE editor? For instance, I would like to have the option for users to select text and apply my desired format. When selected, Tinymce will automatically insert <div class="cust ...

Combining the power of Google Blockly with AngularJS

I am looking for a way to empower advanced users to create and save custom math formulas that will be used in a shopping cart check-out process. These users are not programmers, but can follow instructions easily. The formulas should be editable by the use ...