Interference in the output of .innerHTML leads to disruption

I have been working on a feature to display a calculated price based on the selected quantity for each individual product. I attempted to duplicate the code and modify variable names, but encountered issues with the increase/decrease buttons triggering multiple outputs.

Below is the current code snippet:

$(".incr-btn_mobile").on("click", function(e) {
  var $button = $(this);
  var oldValue = $button.parent().find('.quantity').val();
  $button.parent().find('.incr-btn_mobile[data-action="decrease"]').removeClass('inactive');
  if ($button.data('action') == "increase") {
    var newVal = parseFloat(oldValue) + 1;
  } else {
    // Ensure quantity does not go below 1
    if (oldValue > 1) {
      var newVal = parseFloat(oldValue) - 1;
    } else {
      newVal = 1;
      $button.addClass('inactive');
    }
  }
  $button.parent().find('.quantity').val(newVal);

  var cakePrice = newVal;
  var divobj = document.getElementById('totalPrice');
  divobj.style.display = 'block';
  divobj.innerHTML = "= $" + (cakePrice) * 7.99;
  e.preventDefault();


});
.count-input_mobile {
  position: relative;
  max-width: 1000%;
  max-width: 400px;
  margin: 0px 0;
}

/* CSS styles omitted for brevity */

.button_mobile {
  border: 1px solid #000;
  border-radius: 2px;
  background: none;
  padding: 10px 32px;
  width: 100%;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  cursor: pointer;
  margin-top: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- HTML markup omitted for brevity -->

<div class="count-input_mobile space-bottom">
  <a class="incr-btn_mobile" data-action="decrease" href="#">–</a>
  <input class="quantity" id="ShowButton_value_1_0_mobile" type="text" name="quantity" value="1" />
  <a class="incr-btn_mobile" data-action="increase" href="#">+</a>
</div>

<td>
  <div id="totalPrice">=$7.99</div>
</td>

<!-- Additional instances of count-input elements -->

I am considering creating a new function that uses .incr-btn_mobile_2 instead, but I am open to suggestions for a more efficient solution to avoid redundant css additions.

Answer №1

Your code is close to being correct, but remember that you cannot have multiple identical id attributes. Each id must be unique.

The HTML structure is also incorrect - using <td> without a proper table structure can cause issues.

Please refer to the code snippet below to make the necessary updates:

$(".incr-btn_mobile").on("click", function(e) {
  var $button = $(this);
  var $parent = $button.parent();
  var oldValue = $parent.find('.quantity').val();

  $parent.find('.incr-btn_mobile[data-action="decrease"]').removeClass('inactive');

  var newVal = +oldValue + ($button.data('action') === "increase" ? 1 : -1);

  // Ensure value doesn't go below 1
  if (!newVal) newVal = +!!$button.addClass('inactive');

  $parent.find('.quantity').val(newVal)
  .end().next('.totalPrice').html("= $" + newVal * 7.99);
  e.preventDefault();

});
.count-input_mobile {
  position: relative;
  max-width: 1000%;
  max-width: 400px;
  margin: 0px 0;
}

/* CSS code continues... */

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- Add this HTML snippet to your code -->

Answer №2

The reason for the issue is that both of your result boxes have the same id: totalPrice. To resolve this, you should assign different ids and set the id in the button as a data-target.

<div class="count-input_mobile space-bottom">
  <a class="incr-btn_mobile" data-action="decrease" data-target="totalPrice" href="#">–</a>
  <input class="quantity" id="ShowButton_value_1_0_mobile" type="text" name="quantity" value="1" />
  <a class="incr-btn_mobile" data-action="increase" data-target="totalPrice" href="#">+</a>
</div>

<td>
  <div id="totalPrice">=$7.99</div>
</td>

<div class="count-input_mobile space-bottom">
  <a class="incr-btn_mobile" data-action="decrease" data-target="totalPrice2" href="#">–</a>
  <input class="quantity" id="ShowButton_value_1_5_mobile" type="text" name="quantity" value="1" />
  <a class="incr-btn_mobile" data-action="increase" data-target="totalPrice2" href="#">+</a>
</div>
</td>
<td>
  <div id="totalPrice2">= $7.99</div>
</td>

and here is the JavaScript code:

$(".incr-btn_mobile").on("click", function(e) {
      var $button = $(this);
      var oldValue = $button.parent().find('.quantity').val();
      $button.parent().find('.incr-btn_mobile[data-action="decrease"]').removeClass('inactive');
      if ($button.data('action') == "increase") {
        var newVal = parseFloat(oldValue) + 1;
      } else {
        // Ensure quantity doesn't go below 1
        if (oldValue > 1) {
          var newVal = parseFloat(oldValue) - 1;
        } else {
          newVal = 1;
          $button.addClass('inactive');
        }
      }
      $button.parent().find('.quantity').val(newVal);

      var cakePrice = newVal;
      var divobj = document.getElementById($button.attr('data-target'));
      divobj.style.display = 'block';
      divobj.innerHTML = "= $" + (cakePrice) * 7.99;
      e.preventDefault();
    });

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 a Javascript method to access a sibling property within an object

Is there a way to access a sibling property from a method in JavaScript? This seemingly simple task has proven challenging for me. Take a look at the sample code below. let f = { a: 3, printMyBrother() { console.log(X) } }.printMyBrother f() ...

challenges with website design on Internet Explorer 7

Welcome! This is my HTML code: <div style="width:220px;float:left;" id="radio_text"> <ul style="width:20px;float:left;display:block;"> <li style="list-style:none;line-height:13px;height:13px;float:left;"><input type="radio ...

Issue encountered in AngularJS: struggling to store the localStorage item in the scope variable

I've been trying to save the values from window.localStorage.getItem('job_id.done_tasks') into a $scope variable, but I'm encountering difficulties. Can you please review my code? $scope.done_tasks = {}; $scope.done_tasks = window.loca ...

Tips for creating equal height columns in Bootstrap 4

Working with Bootstrap 4 Beta in an attempt to create two columns that maintain full height regardless of screen size. The code below functions perfectly, ensuring both columns maintain full height across all devices. However, upon inserting the bootstra ...

Tips for implementing autocomplete functionality in AngularJS input fields

I attempted to integrate code from a website (http://jsfiddle.net/sebmade/swfjT/) into my program, but unfortunately, the output did not match what was expected. I am also looking to implement a search function by camera id. Can anyone provide assistance? ...

Employing Isotope/jQuery for organizing posts on Tumblr in columns with the ability to infinitely scroll

Alright so, here we have the classic dilemma where scripts are running before images load. And to make matters more complicated, on Tumblr, there's no way to access image dimensions before they're loaded into the DOM... $('#thumbnails&apos ...

Running on Node.js, the Promise is activated, yet there remains an issue with the function

I've encountered a strange issue that I can't seem to diagnose. It's showing a TypeError: My code is returning 'function is undefined', which causes the API call to fail. But oddly enough, when I check the logs and breakpoints, it ...

Error occurs when using jQuery.ajax on mobile devices such as android or ios

When accessing my website, an ajax request is made to my REST API. It works perfectly on desktop browsers like Chrome, Internet Explorer, and Firefox, as well as on my Windows phone. However, when trying to access it from an Android or iOS device, the XHR ...

Difficulties with integrating tooltips into SVGs

Being a minimalist, I am facing restrictions while working on a website. I desire interactive tooltips to appear when users hover over specific sections of my SVG. However, I also want to incorporate this interactivity within the SVG itself. The challenge ...

What could be the reason why the navbar ul li a instance is not appearing in Bootstrap 4 modal when using an

Can anyone help me solve the issue I'm having with viewing HTML in a Bootstrap 4 modal? Everything shows up except for the navbar ul li a elements. I've searched for a solution everywhere, but haven't found one yet. Please assist! (I want t ...

Variable width items inside an overflow-x container

I'm searching for a solution to create a vertical navigation list that can accommodate elements wider than the container itself. Since users have the freedom to input any names for the items, I cannot predict their width, except maybe by setting a ver ...

What is the correct way to define an abstract method within a class to ensure that an IDE detects and notifies if the abstract method is not implemented

Is there a way to properly define an abstract method in an abstract class and have the IDE notify us if we forget to implement it? I attempted the following approach, but it did not work: export abstract class MyAbstractClass { /** * @abstract ...

Tips for accessing a file in AngularJS

Can AngularJS be used to read files? I am interested in placing the file within an HTML5 canvas for cropping purposes. I was considering implementing a directive. Below is the JavaScript code that I plan to include in my directive: function readURL(input ...

Asynchronously loading images within a div that has overflow: scroll, as they come into view

The setup I have for displaying my content looks like this: <div id="content" style="overflow:scroll;height:500px; width: 500px;"> <div style="width:500px;height:100px;> <img src='http://graph.facebook.com/user1/picture?width= ...

Easiest method for combining elements made in Angular with D3

Exploring various methods to combine D3 and Angular for learning purposes, seeking advice on the approach: The client application is fed a JSON array of nodes and edges from the server. The main component is a graph visualization using D3 force-directed l ...

Formik's setField function is not properly updating the value of an array when using Material UI's autocomplete

When the data is retrieved from the API, it comes in the following format: otherLanguages:[{code:EN,name:"English"},{code:MD,name:"Mandarin"}] I am attempting to initialize the Autocomplete with this data: initialValues: { otherLa ...

Forming a header area by utilizing a 960 Grid container

I'm in the process of designing a website utilizing the 960 Grid system. The header consists of three parts: the logo, the navigation, and the login form. I've implemented media queries to center both the logo and the login section when the pag ...

The Ionic application encounters an issue with the $stateParams being

Can someone assist me with resolving an issue related to ionic $stateParams? Here is the state configuration: .state('tabs.categories', { url: "/categories/:parentID", views: { 'categories-tab': { templateU ...

Maintaining aspect ratio while resizing images: A foolproof guide

I've been working on image editing and encountered a bit of trouble with aspect ratios. <img src="big_image.jpg" width="900" height="600" alt="" /> As you can see, the height and width are already specifi ...

Nested arrays in the JavaScript programming language

Is this JavaScript code accurate: var options = []; options.push(["Tom","Smith"]); options.push(["Mary","Jones"]); where each item in options is a two-element array of strings. I plan to add items to options using a for loop. Furthermore, can I i ...