Performing addition and multiplication operations on separate identifiers with the help of Jquery

Currently, I am working on developing a shopping cart website and I am new to using Jquery. My layout involves the need to increment and decrement values by one when the plus and minus button is pressed. Additionally, the total price value should also be adjusted accordingly. Below is the Jquery code I have attempted:

//Add and Subtract
$("#add").on('click',function()
{
        if(parseInt($("#total input").val())>=0)
        $("#total input").val(parseInt($("#total input").val())+1);
});
$("#sub").on('click',function()
{
        if(parseInt($("input").val())>0)
        $("#total input").val(parseInt($("#total input").val())-1);
});

Here is my HTML code:

<div class="btn_group" id="total">
<a href="#" class="btn_add_subtract" id="add">
+
</a>
<input type="text" class="quantity_value" value="0"/>
<a href="#" class="btn_add_subtract" id="sub">
-
</a>
</div>

However, I am facing an issue where all the data in the list is being changed when I try to increment or decrement the value. Can anyone suggest a better approach for me to achieve this functionality?

Thank you

Answer №1

One way to approach this issue is by creating a basic framework for the problem, with the main focus being on how to locate the input element in relation to the button that was clicked.

To ensure that the same functionality can be applied to multiple buttons, it is advisable to assign the same class to these elements (add/minus buttons) for easy targeting.

$('.add').click(function() {
  $(this).prev().val(function(i, val) {
    return (+val || 0) + 1;
  });
});
$('.minus').click(function() {
  $(this).next().val(function(i, val) {
    val = (+val || 0) - 1;
    return val < 0 ? 0 : val;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <span class="minus">-</span><input name="x"/><span class="add">+</span>
</div>
<div>
  <span class="minus">-</span><input name="x"/><span class="add">+</span>
</div>
<div>
  <span class="minus">-</span><input name="x"/><span class="add">+</span>
</div>

Answer №2

Avoid using ids and opt for classes instead.

Organize elements for each item within a container element:

<!-- Repeat this block for every item -->
<div class="itemContainer">
    <div class="total">$</div>
    <button type="button" class="sub">-</button>
    <input type="text" class="quantity" value="0"/>
    <button type="button" class="add">+</button>
</div>

To handle click events, use this to target the clicked button, then utilize .closest() to move up to the container and .find() to locate other elements within.

$(".add").on('click',function()
{
    var $itemContainer = $(this).closest('.itemContainer'),
        $quantity = $itemContainer.find('.quantity'),
        $total = $itemContainer.find('.total');

    // Perform operations on quantity input and total div for this specific item.
});

Answer №3

Recommendation: Use class in place of id -

$(".add").on('click',function()
{
        var input = $(this).closest(".total input");
        if(parseInt(input.val())>=0)
        input.val(parseInt(input.val())+1);
});
$(".sub").on('click',function()
{
        var input = $(this).closest(".total input");
        if(parseInt(input.val())>=0)
        input.val(parseInt(input.val())-1);
});

Hopefully this solution proves to be useful for you.

Answer №4

Suppose you have a set of buttons and a textbox enclosed in the same container;

$("#add").on('click',function()
{
        if(parseInt($("#total input").val())>=0)
        $(this).parent().find("#total input").val(parseInt($(this).parent().find("#total input").val())+1);
});
$("#sub").on('click',function()
{
        if(parseInt($("input").val())>0)
        $(this).parent().find("#total input").val(parseInt($(this).parent().find("#total input").val())-1);
});

I recommend using a common variable for repetitive selections.

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

Utilize Firebase for seamless signup/login process leveraging web3 integration

Looking to implement a unique authentication method using web3 and Metamask in place of traditional email and password signups for Firebase. The challenge lies in handling the signup process - how can this be achieved? One potential solution is utilizing ...

"Troubleshooting: Issues with jQuery Counter Functionality

Hey there, I'm new to JavaScript and jQuery! I've got this form set up with Bootstrap's disabled class: Note: the 'disabled' class in bootstrap properly disables and enables the button based on conditions. <form action="" met ...

What is the best way to include a permanent placeholder within an input field?

I'm trying to insert a font icon inside an input field using the following method: <input type="text" name="your name" placeholder="&#xe00b; YOUR NAME" style="font-family:Flaticon" class="restrict"> Currently, the font icon &#xe00b; is ...

Tips for fading out two elements after completing a drag and drop action

Visit this Codepen for more examples - Codepen I have been developing a drag and drop feature in my application. Once the item is dropped, it transitions from red to green and fades out smoothly. The droppable element behind the draggable should also fad ...

Using jQuery to incorporate a variable into JSON schema markup

For my current project, I am attempting to extract the meta description and incorporate it into JSON schema markup. However, I am facing difficulty in passing the variable properly into the JSON structure. My initial approach was as follows: <script&g ...

Scrollbar customization feature not functional in Firefox browser

I recently finished developing a website and I have customized the main vertical scrollbar. Unfortunately, I am facing an issue where it works well on Google Chrome and Safari but not on Mozilla Firefox. Does anyone have any suggestions on how to trouble ...

Looking for a quicker loading time? Opt for a shortened version of CSS

Most of the images on my website are optimized using sprite sheets, where multiple images are combined into one file to enhance user experience. This method reduces the number of server requests for individual images. However, I'm facing an issue whe ...

Retrieve JSON information from an asmx file using a C# webpage

I'm working with code that looks like this: [ScriptService] public class Titles : WebService { List<Title> Title = new List<Title>(); SqlConnection connection; SqlCommand command; SqlDataReader reader; [WebMethod()] ...

How to achieve a seamless iframe effect using CSS

With the introduction of new HTML5 iframe attributes, there are now more options available. One such attribute is the seamless attribute, which has the ability to: Create an iframe that appears to be seamlessly integrated into the containing document. ...

Instructions for showing a "read more" and "read less" link when the text goes beyond a

I am pulling paragraph content from the database and displaying only 300 characters on the screen, with a "read more" option for the user to see the rest of the content. However, I am facing an issue where I also need to include a "less" option for the us ...

The CSS filter failed to function properly as the Chrome Inspector is displaying a strik

I recently encountered an issue with my website where I was trying to apply a CSS dropshadow effect to an item, but it just wasn't working. Upon inspecting the code in Chrome Inspector, I noticed a strike through on the rule (refer to screenshot). Eve ...

pictures in photo display

Please check out my codepen project: html code: <body> <div class="thumbnails"> <a href="#"><img src="http://s30.postimg.org/4yboplkxd/dotty.jpg" width="100" height="100"></a> <a href="#"><img src="http:// ...

Updating the forward slash and numerical values within javascript or jQuery

I looked through various resources but couldn't find a suitable solution for my issue. I have a URL string like: http://localhost:8888/mypage/post/1/ The post number can vary from 0-9. Now I need to modify that string by replacing "post/1/" with "ne ...

Utilizing jQuery AJAX in Internet Explorer 8

My current approach involves using a get request with $.ajax when the user submits a form. However, I'm unsure if my method (attaching a click event to the form button) is the most efficient or standard way to achieve this. If there is a more effecti ...

Wait for the scope value to become available before executing the directive or div

I have a unique directive created for SoundCloud that necessitates the SoundCloud URL. The URL is fetched from the database using the $http service, but the issue arises when the div for the directive is loaded before the URL value is defined. The code fo ...

Utilizing the <a> element within a Thymeleaf loop

I'm looking to use Thymeleaf to display a list of links in my project. Below is the code I used successfully for displaying the links: <div class="col-12 col-md-6" th:each="ApplicationVO: ${ApplicationList}"> & ...

I kindly request your assistance in resolving the issues with the append() and empty

Here is some code I've been working on: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script> $(document).ready(function(){ ...

Angular disrupts the functionality of jQuery slideshow

While working on this template, I encountered issues with the functionality after integrating Angular into the application. Although I managed to fix most of them, I'm facing difficulty getting the slideshow to function properly. Here is the HTML cod ...

Incorporate a dynamic fading effect for text and images using JQuery

I successfully implemented a Crossfade effect using Jquery: function doAnimationLoop(o, n, t, i, a) { fadeInOut(o, n, t, i, function() { setTimeout(function() { doAnimationLoop(o, n, t, i, a) }, a) ...

Positioning two divs to the right of another div

I am facing an issue with aligning the menu and categories divs to the right of the logo div in the following example: jsfiddle. I want them to remain stacked one under another as they are currently, but I am unable to achieve the desired display. Any ass ...