Picking the following div using a button and updating its content

I am currently working on a project that involves 4 div elements, each with its own value (for example: 0). There is also a button with plus and minus functionality to change the values in each box. Additionally, there is a "set next" button to move on to the next box and repeat the process.

The challenge I am facing is how to efficiently select the next div, update its value using the same plus and minus buttons, and then move on to the subsequent div until reaching the end. The process should then loop back to the first div. Below is an excerpt of my code:

<div class="code_div">
    <div class="code_area">
        <p id="number1">00</p>
    </div>
    <div class="code_area2">
        <p id="number2">00</p>
    </div>
    <div class="code_area3">
        <p id="number3">00</p>
    </div>
    <div class="code_area4">
        <p id="number4">00</p>
    </div>
var value = 0;
var plus = false;
var minus = false;

$(document).ready(function() {
    $('#set_next').click(function() {
    });

    $('#minus').click(function() {
        minus = false;
        plus = true;
        if (plus == true) {
            value -= 5;
        }
        displayValue()
    });

    $('#plus').click(function() {
        minus = true;
        plus = false;
        if (minus == true) {
            value += 5;
        }
        displayValue() 
    });
});

function displayValue() {
    document.getElementById("number1").innerHTML = value;
}

If anyone has any insights or suggestions on how to tackle this issue, I would greatly appreciate it!

Answer №1

Keeping it simple is key here. Instead of using a list of divs, opt for a list element. Even if you prefer to stick with your current markup, this example should provide some insight on how to execute this.

var $items = $('ul li'),
    qtItems = $items.length,
    activeItem = 0;

$('#setnext').click(function () {
  $items.removeClass('active').eq(++activeItem % qtItems).addClass('active');
});
                   
$('#plus, #minus').click(function () {
  var currvalue = $items.eq(activeItem % qtItems).text();
  this.id === 'plus' ? currvalue++ : currvalue--;
  $items.eq(activeItem % qtItems).text(currvalue);
});
ul {
  list-style: none;
}

ul li {
  display: inline-block;
  margin: 0 1em;
  padding: 1em;
  background-color: green;
  opacity: .5;
}

li.active {
  opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="active">0</li>
  <li>0</li>
  <li>0</li>
  <li>0</li>
</ul>

<button id="setnext">set next</button>
<button id="plus">plus</button>
<button id="minus">minus</button>

If simplifying your markup isn't an option, here's another straightforward solution using your initial html structure. In this version, unnecessary classes and ids are eliminated for a cleaner approach.

Answer №2

let number = 0;
let add = false;
let subtract = false;
let counter=1;
$( document ).ready(function() {

$('#set_next').click(function() {
counter++;
//update
$("#number"+counter).css("color","blue");
if(counter==5){
counter=1;
}
});

 $('#minus').click(function() {
       subtract = false;
       add = true;
        if (add == true){
        number -= 5;
    }
displayNumber()
    });

 $('#plus').click(function() {
       subtract = true;
       add = false;
    if (subtract == true){
         number += 5;
    }
displayNumber() 
    });
});

function displayNumber(){
        document.getElementById("number"+counter).innerHTML = number;
}

Answer №3

Although your code could use some refining (I can suggest a cleaner approach if you're interested) Check this out on JSFiddle Does something like this work for you? Here's the HTML code:

<div class="code_div">
<div class="code_area">
<p id="number1">00</p>
</div>
<div class="code_area2">
<p id="number2">00</p>
</div>
<div class="code_area3">
<p id="number3">00</p>
</div>
<div class="code_area4">
<p id="number4">00</p>
</div>
    <button id="set_next">set next</button>
    <button id="minus">minus</button>
    <button id="plus">plus</button>

Javascript:

var current = 1;
    var max = 4;

    var value = 0;
    var plus = false;
    var minus = false;
    $( document ).ready(function() {

    $('#set_next').click(function() {
        if( current < max )
        {
            current+=1;
        }
        else
        {
            current = 1;
        }
     value = parseInt($("#number"+current).text());
    });

     $('#minus').click(function() {

           minus = false;
           plus = true;
            if (plus == true){
            value -= 5;
        }

    displayValue()

        });


     $('#plus').click(function() {

           minus = true;
           plus = false;
        if (minus == true){
             value += 5;
        }
    displayValue() 

        });

    });


    function displayValue(){

            document.getElementById("number"+current).innerHTML = value;

    }

EDIT: Remember to recalculate the value of the current element whenever you switch focus to a new one (other than that, the chosen solution is also great)

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

Having issues with ajax posting functionality

Is the following form correct? <form> <input type="submit" value="X" id="deleteButton" onclick="ConfirmChoice(<?php echo $id; ?>)" /> </form> Here is the function associated with the form: <script type='text/javasc ...

How does the AngularJS Dependency Injection system determine the names of the arguments it needs to inject?

Here is an example directly from the official website: function PhoneListCtrl ($scope, $http) { $http.get('phones/phones.json').success(function(data) { $scope.phones = data; }); $scope.orderProp = 'age'; } The $s ...

Angular 16: ngCharts Error - Unable to Iterate Over registerables Property

ERROR: Uncaught (in promise): TypeError: chart_js__WEBPACK_IMPORTED_MODULE_0__.registerables is not iterable (cannot read property undefined) TypeError: chart_js__WEBPACK_IMPORTED_MODULE_0__.registerables is not iterable (cannot read property undefined) at ...

Despite using callbacks when passing props in React JS components, the rerendering still occurs

In my React project, I implemented callbacks to prevent excessive rerendering due to the large amount of data being displayed and numerous buttons that trigger these rerenderings when clicked by the user. The useCallback hooks are effective in preventing ...

Toggle visibility of table columns by selected options (using jQuery)

I am seeking to create a dynamic table that only shows specific columns based on the selection in a dropdown menu. <table> <thead> <td colspan="5"> <SELECT name="menu"> <option value="eur">EUR</option> & ...

Improving code efficiency with jQuery through optimizing repetitive tasks

Seeking advice on optimizing my code for fading in and out the navigation when scrolling below 100px, as well as on hover. Is there a way to store repetitive lines of code in a variable and use it when needed? $(document).ready(function () { $(window).s ...

Navigating Overlays with Python and Selenium

driver.find_element_by_class_name("lnkClassInfo").click() time.sleep(2) element = driver.find_element_by_css_selector("#popup input[value='BOOK THIS CLASS NOW']") driver.execute_script("arguments[0].click();", element) ERROR: selenium.common.exc ...

Problems with Emulating Chrome | Using Media Queries

Currently, I am in the midst of testing my responsive website and I have encountered an issue with the Chrome emulator. When I select a specific device like "iPhone 6", the responsive views are not displaying correctly. Instead, unsightly scroll bars appea ...

Populating dependent dropdown menus with database values while in edit mode

I'm struggling with filling dependent dropdowns. The dependent dropdowns work fine when entering data - I select a State from the dropdown and the dependent dropdowns reload based on that selection. The issue arises when I try to edit information. Th ...

Creating beautiful user interfaces with Material UI and React

I'm currently exploring how to integrate Material UI into my React project. After successfully installing the module, I attempted to create a custom button component. Here is my Button.js file: import React from 'react'; import FlatButton ...

Enhance npm package by implementing custom functionality with React Component

I have designed an app that bears a striking resemblance to the following code: class MyCustomApp extends React.Component { constructor (props) { super(props) this.state = { tags: [ { id: 1, name: "Oranges" }, { id: 2, ...

Create dropdown options from JSON data

I'm attempting to populate a dropdown menu using a JSON response retrieved from an API. let dropdown = $('#LA_picker'); dropdown.empty(); dropdown.append('<option selected="true" disabled>Choose State/Province</option>& ...

End your Idp session and log out using passport-saml

Encountering a 400 bad request error when attempting to log out a user from the idp session. Despite successfully logging out the user from the application/passport session, they remain logged in to the idp session. The logout and callback endpoints are c ...

Check two arrays by comparing the first array and return the values that have a partial match, even if they are not

Hi there, I'm trying to filter my array based on another array, even if the values don't match exactly. Here is an example of what I'm working with: First array: [Mon Sep 09 2019 00:00:00 GMT+1000 (Australian Eastern Standard Time), Tue Sep ...

What is the best way to transfer a jQuery Raty score to Wtforms, Flask, or Python?

Wishing you a fantastic start to the new year! I've been attempting to retrieve the score (Number type) from jQuery Raty using a wtforms form. Unfortunately, I haven't been able to figure out how to successfully send the score number to my backe ...

Enhance text content effortlessly with an automated text augmentation feature

Essentially, what I'm wondering is whether there exists a program that can automatically add HTML tags to the text you input. For instance: Let's say I type in: "The world is beautiful" The program would then transform it into: <p align="c ...

Converting an HTMLElement to a Node in Typescript

Is there a method to transform an HTMLElement into a Node element? As indicated in this response (), an Element is one specific type of node... However, I am unable to locate a process for conversion. I specifically require a Node element in order to inp ...

Are you accessing the site on a variety of gadgets?

I am currently working on a website with the goal of making it responsive. So far, it looks great on desktops and mobile phones like the iPhone and Galaxy S4. However, I am encountering difficulties in making the website look like it is on a mobile phone w ...

Information disappearing upon returning to a previous screen

Currently, I am developing a web application using AngularJS and HTML. As part of the application, I created a dashboard on the home screen (referred to as Screen A) that displays a list of clients with a summary. When a client is clicked, it navigates t ...

Tips for implementing react portal functionality in react 15

Working on my current project with react 15, I am looking to display an overlay on the screen when a dropdown is opened. While React 16 allows us to utilize React portal to render children into a DOM node outside of the parent component's hierarchy, h ...