Navigating through DOM event termination

I'm encountering a minor issue. I have a form containing a few inputs[type="text"] wrapped in div elements (plus and minus). How can I increment and decrement these inputs without having to create variables, classes, or ids for each element? Someone suggested using arrays, but I'm unsure of how to approach this...

The current solution involves assigning classes to each tag...

var child = document.querySelector("#child");
var adult = document.querySelector("#adult");
var rooms = document.querySelector("#rooms");
var plusChild = document.querySelector(".plus_child");
var minusChild = document.querySelector(".minus_child");

var childV = child.value;
var adultV = adult.value;
var roomsV = rooms.value; 

plusChild.addEventListener("click", function(){
    if(childV<10){
        childV++;
        child.value = "" + childV;
    }
});

minusChild.addEventListener("click", function(){
    if(childV>0) {
        childV--;
        child.value = "" + childV;
    }
});
 
.main-form {
    width: 500px;
    margin: 0 auto;
}
.input {
    display: inline-block;
    width: 100px;
    height: 15px;
    background: none;
    outline: none;
}
.plus {
    display: inline-block;
    background: #999999;
    width: 15px;
    height: 15px;
}
.minus {
    display: inline-block;
    background: #999999;
    width: 15px;
    height: 15px;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    
    <form action="" class="main-form">
        
        <div class="input-item">
        <span>child</span>
        <div class="toggle plus plus_child">+</div>
        <input type="text" class="input" placeholder="0" id="child">
        <div class="toggle minus minus_child">-</div>
        </div>
        <br>
        <div class="input-item">
        <span>adult</span>
        <div class="toggle plus">+</div>
        <input type="text" class="input" placeholder="0" id="adult">
        <div class="toggle minus">-</div>
        </div>
        <br>
        <div class="input-item">
        <span>rooms</span>
        <div class="toggle plus">+</div>
        <input type="text" class="input" placeholder="0" id="rooms">
        <div class="toggle minus">-</div>
        </div>
        
        
    </form>
    
    
   
    <script src="script.js"></script>
</body>
</html>

Answer №1

To easily manipulate the value of an element with the ID "child", you can accomplish it like this: var child = document.getElementById("child"); child.value++; or child.value--;

Answer №2

The key is understanding the structure of the DOM tree. Instead of giving every element an ID to attach a handler, you just need to locate its position in the tree and work from a known reference point.

For example:

<div id="attach_to_me">
   <button>+</button>
   <button>-</button>
</div>

In this case, the buttons themselves don't perform any action individually. However, you can easily handle both buttons with one click event like this:

$('#attach_to_me button').on('click', function(e) {
    char = this.text();
    if (char == '+') { do_plus(); }
    if (char == '-') { do_minus(); }
});

This single click event manages both buttons. If you need to identify which specific button was clicked, you can use e.target to pinpoint the clicked element. This allows you to navigate the tree effectively. For instance, if you have multiple buttons in different rows:

<tr>
   <td>foo</td><td><button>x</button></td>
   <td>bar</td><td><button>x</button></td>
   <td>baz</td><td><button>x</button></td>
</tr>

$('td button').on('click', function (e) {
    clicked_button = e.target;
    e.target.parentNode.previousSibling.text(); // `bar`
});

Starting from the clicked button, you can navigate up or across the tree to access the text in the adjacent <td>.

Answer №3

If the structure of the HTML remains constant, you can make use of the previous and next sibling functions.

Here is an example implementation:

function handleFirst(Element) { // code for handling first sibling }
function handleSecond(Element) { // code for handling second sibling }
var textInputs = document.querySelectorAll('input[type=text]');
for(var i=0; i < textInputs.length; i++) {
    textInputs[i].previousSibling.addEventListener('click', handleFirst);
    textInputs[i].nextSibling.addEventListener('click', handleSecond);
}

Make sure to refer to the opposite sibling function inside your click handlers in order to target the respective input element.

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

How do I pass input values when calling an AJAX function to submit a form in HTML?

Utilizing a modal to submit new data via AJAX API consumption. Although sending the data through the API is not an issue, my lack of HTML skills makes it confusing on how to pass form data values. This scenario involves displaying a modal for users to in ...

What is the best way to exhibit information from a get request within an option tag?

My GET request is fetching data from a REST API, and this is the response I receive: { "listCustomFields": [ { "configurationType": null, "errorDetails": null, "fieldId" ...

Developing a website that utilizes Node.js for browser-based RSS scraping

Although I have some experience with coding, I am fairly new to Javascript and web development. Currently, I'm working on creating a webpage that centers around scraping an RSS feed from the National Weather Service (for example, ) and parsing the in ...

Enter data into the appropriate columns

Within my Angular 6 application, I am creating a table with the following structure: Html: <table> <thead> <tr> <th> Property Details &nbsp; &nbsp; &nbsp; &nbsp; ...

Creating a circular image in a responsive navigation bar

Currently, I have a chat navigation bar with divs representing different users, each displaying a photo of the user. My goal is to have these photos displayed as perfect circles. To achieve this, I am using padding-bottom and width properties. However, I a ...

What is the method for assigning 'selective-input' to a form field in Angular?

I am using Angular and have a form input field that is meant to be filled with numbers only. Is there a way to prevent any characters other than numbers from being entered into the form? I want the form to behave as if only integer keys on the keyboard ar ...

Connect cells within an HTML table by drawing a line between them

While attempting to create a visually appealing floor plan, I have been unable to find any Javascript/jQuery libraries that meet my needs. My input is a text file with 0s and 1s (a sample 10x10 matrix), where the 1s represent walls. After processing the in ...

Is it possible to submit a form to two separate pages individually rather than simultaneously?

I am currently facing an issue where I need to submit a page to two different pages depending on which button triggers the submission. Both of these pages should be able to retrieve the $_POST data that is being sent. The code snippet shared below shows wh ...

Updating HighCharts with fresh data through Ajax

I'm currently in the process of replacing the highcharts that I initially loaded through ajax. The idea is to obtain new values from the user, pass them via Ajax, and then display an entirely new graph (with a different type and data). Here's wha ...

Error: non-integer values cannot be used as indices when examining an array containing dictionaries

Encountering a Type Error when attempting to determine if a key with a specific value exists: "string indices must be integers." if not any(dObj["date"] == wholeDay for dObj in userPunchCard.clock): status = "Clock In" content = { "name" : user.n ...

Guide on connecting various information to a jquery element through .data() within a custom plugin

I have come across a problem with my two plugins $.fn.expect = function (expectation) { return this.each(function () { $(this).data('expectation', expectation); }); } $.fn.isExpected = function () { return $(this).dat ...

Improving the method for calculating the sum of a property value within an array

I have a similar structure as below: $scope.traveler = [ { description: 'Senior', Amount: 50}, { description: 'Senior', Amount: 50}, { description: 'Adult', Amount: 75}, { de ...

Retrieve resources from a pre-built npm package on-the-fly

Question regarding the creation of npm packages and the ability to dynamically request resources from one package in another. Imagine I have a collection of images in package A, along with JavaScript logic to fetch them: // Inside package B import Compone ...

Forming a collection of different classes

When attempting to create an array of class Person within the Donator class, I encountered the error message: "error: constructor Person in class Person cannot be applied to given types;". What could be causing this issue? Could there be missing or incorr ...

Working with Angular.js ng-repeat and conditions

I am utilizing ng-repeat to loop through a key/value array. In cases where the key matches 'First Name', I want to bind it to firstName. Being new to angular.js, I wonder if there is a more efficient way of achieving this? Essentially, I have a k ...

Flickering screen observed during authentication verification with local storage in NextJS

After successfully logging in with my email and password on my NextJS frontend, I receive an accessToken from the backend (Laravel Sanctum) which I then store in local storage. When accessing a protected page like /profile, I need to ensure that the token ...

The Javascript validation error for radio buttons briefly appears for a moment when it should stay visible

After reviewing about 30 examples and testing them out, I have decided to post my question since none of the examples seem to be working for me. I am not an expert in JavaScript, but I assumed that validating a simple radio button should not be too diffic ...

Unable to apply insertRule with keyframes

When using CSS without keyframes, insertRule functions perfectly. However, if a CSS with keyframes is used, an error occurs: Failed to execute 'insertRule' on 'CSSStyleSheet': Failed to parse the rule ... The following code works: ...

What is the best way to style nodes in a Force Directed Graph using CSS in D3?

Currently, I am developing a Force Directed Graph using D3 and managed to make it work with svg circles for the nodes. However, when attempting to use div elements along with CSS left and top properties, the positioning of the nodes seems to be incorrect. ...

What is the reason behind the consistent size of 8 for pointers to arrays in C programming language?

Here is a simple code that compares the size of an array itself and the size of a pointer to the array. #include <stdio.h> int main(){ int numbers[100] = {1, 0,}; int (*ptr) = numbers; printf("Size of array using arra ...