Even as I raise the value of the text content, the decrease button remains unresponsive

I am facing a challenge in enabling the decrease button only when the value of textcontent is higher than 1. My intention is to gradually increase the value from 1 upwards while allowing the decrease button, but once the value reaches 1, I want the decrease button to be disabled.

var newDiv = document.createElement('div')
var increaseButton = document.createElement('button')
var decreaseButton = document.createElement('button')

newDiv.textContent = 1
document.body.appendChild(newDiv)
document.body.appendChild(increaseButton)
document.body.appendChild(decreaseButton)


increaseButton.setAttribute('id', 'increase')
decreaseButton.setAttribute('id', 'decrease')

if(Number(newDiv.textContent) == 1) {
    decreaseButton.setAttribute('disabled', '')
}else {
    increaseButton.removeAttribute('disabled')
}

increaseButton.onclick = () => {
    newDiv.textContent = Number(newDiv.textContent) + 1
}

decreaseButton.onclick = () => {
    newDiv.textContent = Number(newDiv.textContent) - 1
}

Answer №1

Check out this code snippet on jsFiddle

var newDiv = document.createElement('div')
var increaseButton = document.createElement('button')
var decreaseButton = document.createElement('button')

newDiv.textContent = 1
document.body.appendChild(newDiv)
document.body.appendChild(increaseButton)
document.body.appendChild(decreaseButton)

increaseButton.setAttribute('id', 'increase')
decreaseButton.setAttribute('id', 'decrease')

function checkAndDisable() {
  if(Number(newDiv.textContent) == 1) {
    decreaseButton.setAttribute('disabled', '')
  }else {
     decreaseButton.removeAttribute('disabled')
  }
}

checkAndDisable();

increaseButton.onclick = () => {
    newDiv.textContent = Number(newDiv.textContent) + 1;
    checkAndDisable();
}

decreaseButton.onclick = () => {
    newDiv.textContent = Number(newDiv.textContent) - 1;
    checkAndDisable();
}

Remember to call the function that checks for disabling when the value changes. Also, there seems to be a typo in the code where

increaseButton.removeAttribute('disabled')
should be fixed.

Answer №2

It's important to note that the disabled property needs to be set within the click event handlers in order for it to take effect when the buttons are clicked. Here is an example demonstrating how to properly handle the disabled property:

var newDiv = document.createElement('div');
var increaseButton = document.createElement('button');
increaseButton.textContent = 'Increase';
var decreaseButton = document.createElement('button');
decreaseButton.textContent = 'Decrease';

newDiv.textContent = 1;
document.body.appendChild(newDiv);
document.body.appendChild(increaseButton);
document.body.appendChild(decreaseButton);

increaseButton.setAttribute('id', 'increase');
decreaseButton.setAttribute('id', 'decrease');

decreaseButton.setAttribute('disabled', true);

increaseButton.onclick = () => {
  newDiv.textContent = Number(newDiv.textContent) + 1;
  enableDisable();
}

decreaseButton.onclick = () => {
  newDiv.textContent = Number(newDiv.textContent) - 1;
  enableDisable();
}

function enableDisable() {
  if(Number(newDiv.textContent) == 1) {
    decreaseButton.setAttribute('disabled', true);
  } else {
    decreaseButton.removeAttribute('disabled');
  }
}

Answer №3

If you're looking to monitor changes in a dynamically created DIV, consider using a MutationObserver.

var newDiv = document.createElement('div');
var increaseButton = document.createElement('button');
var decreaseButton = document.createElement('button');
var observerOptions = { childList: true }; // Necessary observer options

newDiv.textContent = 1;
document.body.appendChild(newDiv);
document.body.appendChild(increaseButton);
document.body.appendChild(decreaseButton);

increaseButton.setAttribute('id', 'increase')
decreaseButton.setAttribute('id', 'decrease')

// Set up the MutationObserver
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (Number(newDiv.textContent) == 1) {
      decreaseButton.setAttribute('disabled', '')
    } else {
      decreaseButton.removeAttribute('disabled')
    }
  });
});
// Start observing
observer.observe(newDiv, observerOptions);

increaseButton.onclick = () => {
  newDiv.textContent = Number(newDiv.textContent) + 1
}

decreaseButton.onclick = () => {
  newDiv.textContent = Number(newDiv.textContent) - 1
}

In this scenario, using a simple function might be the most straightforward solution. 😉

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

Strategies for Handling Logic in Event Listeners: Choosing Between Adding a Listener or Implementing a Conditional "Gatekeeper"

What is the most effective way to manage the activation of logic within event listeners? In my experience, I've discovered three methods for controlling the logic contained in event listeners. Utilizing a variable accessible by all connected sockets ...

Having difficulty retrieving values while using async-await

Utilizing the code below has been successful for me. I managed to retrieve the data in the spread (then), returning a http200 response. Promise.all([ axios({ method: 'post', url: 'https://oauth2.-arch.mand.com/oauth2/token&a ...

Enhance the Header component by incorporating a logout button that seamlessly navigates with the NextJS App

Currently, I am utilizing NextJS 14 with App router alongside Spring Boot on the backend. Within my application, I have both public and private routes set up. For the private routes, users are required to log in through a designated login page. Upon succes ...

My SF2 app is experiencing issues with AngularJS integration

I am currently developing a straightforward API using Symfony2 and now I am experimenting with integrating AngularJS into my bundle to visualize the results of my API calls. How can I effectively implement AngularJS? I initiated a bundle via app/console ...

Activating Bootstrap modal when a navigation link is clicked

Just started a site for a client and new to Bootstrap. I've got the layout down - full-width page with "Top Nav" within the nav bar, looking to create a modal effect drop-down. When clicking on "About", it should trigger the .modal function. However, ...

Ways of converting a negative lookbehind into an ES5-friendly expression

In my code, I have a RegExp that works perfectly, but it only functions with ES2018 due to its use of negative lookbehinds. The problem is that a library is using this RegExp function, so modifying how it's used is not an option. I attempted to add n ...

Using TypeScript to define callback functions within the Cordova.exec method

I'm encountering an issue with the TypeScript definition for Cordova. The codrova.d.ts file doesn't allow for any function arguments in the success-callback and error-callback. To better illustrate my problem, here's a small example: Here ...

Is Jade monitoring *.jade files?

Though I am not sure of the internal workings of Jade, my best guess is that it compiles each template file once and then employs a compiled and cached version for subsequent HTTP requests. One intriguing observation I have made while running my Express a ...

Are there any issues arising from conflicting jQueries?

Hello, I am trying to implement EasyUI GridView and Tab in Asp.net MVC4 by placing two Grids inside a Tab. However, I am facing an issue with this setup. I have included the necessary Scripts and CSS in My Layout: <link href="@Url.Content("~/Conten ...

Calculate the total duration between two times and, if the difference is more than 10 minutes,

I need to calculate the duration between two dates, start_time and end_time. If the minutes component is greater than 10, I want to round up the hours component. For example: 12 minutes different - rounded up to 1 hour 1 hour 31 minutes difference - roun ...

Tips for designing rainbow-themed elements (hyperlinks) using CSS to incorporate multiple colors

When customizing link styles in D3.js, it's common to adjust the color of the links. For instance, in the code snippet below, I've created thick links with a width of 10 and colored them grey. link = svg.append("g") . . . .style("stroke", "grey" ...

Monitoring page reload with JavaScript

Here is an example of tabbed content: <div class="tab"> <button class="tablinks" onclick="openCity(event, 'NewYork')" id="defaultOpen">New York</button> <button class="tablinks" onclick="openCity(event, 'LosAngeles& ...

Understanding the flattening process of arrays using JavaScript - Detailed explanation required

Currently, I am immersed in the captivating world of Eloquent JavaScript. However, I have hit a roadblock with one of the exercises that involves flattening a multi-dimensional array. Despite my best efforts, I have been unable to crack the code. After f ...

AngularJS allows a function to return an array value, which can be displayed in separate blocks on

Building a program that involves working with an AngularJS array. I need to showcase the elements of the AngularJS array, returned by a function, in an organized manner. Each element should be displayed correspondingly - for example, 'first' cont ...

Am I on track with this observation?

I am currently using the following service: getPosition(): Observable<Object> { return Observable.create(observer => { navigator.geolocation.watchPosition((pos: Position) => { observer.next(pos); observer.c ...

Discovering intersections between Polylines on Google Maps - a comprehensive guide

I'm currently developing a project involving a unique twist on Google Maps, focusing exclusively on natural hiking paths. My routes are built using GPX files converted into Google Maps polylines. Is there an efficient way to identify the intersection ...

Learn how to manipulate the DOM by dynamically creating elements and aligning them on the same line

Providing some context for my page: The section I have always contains a single input field. Below that, there is an "add" button which generates additional input fields. Since only one field is required on the screen, the following fields come with a "de ...

Using Mocha in Node to make XMLHttprequests

Currently, I am experimenting with using node-xmlhttprequest. Here is an example of what I have been working on: // f.js (function() XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest xhr = new XMLHttpRequest() xhr.open('GET ...

Working with MySQL in Node.js using async/await

Struggling with utilizing async/await in Node.js with MySQL as it consistently returns an undefined value. Can someone shed light on what could be causing this issue? See my code snippet below. const mysql = require('promise-mysql'); var co ...

AngularJS click directives and Google Chrome's content protection policy

Here is an interesting scenario I encountered recently. The new Google Chrome's Content Security Policy now prohibits the use of inline scripts or event handlers like onclick or ontouch within the HTML itself. This means that we are required to write ...