Tips for adjusting the value of a textbox up and down

I am facing an issue with my booking flight form that is supposed to take input from users regarding the number of travelers. I have three textboxes for Adult, Children, and Infants respectively, along with a main textbox to display the final result. However, the functionality seems to not be working as intended.

Here is the code snippet I have implemented:

$(function() {
  $(".button-click a").on("click", function() {

    var $button = $(this);
    var oldValue = $button.closest("ul").prev().val();

    if ($button.text() == "+") {
      var newVal = parseInt(oldValue) + 1;

    } else {
      // Do not allow decrementing below zero
      if (oldValue > 0) {
        var newVal = parseInt(oldValue - 1);
      } else {
        newVal = 0;
      }
    }
    $button.closest("ul").prev().val(newVal);
    var total_value = 0;
    $(".cat_textbox").each(function() {
      total_value += parseInt($(this).val());
    });
    $(".main").val(total_value);
  })
});
<html>
<head>
  <title>Input Number Incrementer</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>

<body>
  <label>
    Total Number of Travelers:
    <input type="text" class="main" value="0" placeholder="" />
  </label>
  <br/>
  <br/>
  <label>
    Adults
    <ul class="button-group button-click">
      <li><a href="#" class="small button secondary"><i class="fa fa-plus"><span class="hide">+</span></i></a>
      </li>
      <input type="text" class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" />
      <li><a href="#" class="small button secondary"><i class="fa fa-minus"><span class="hide">-</span></i></a>
      </li>
    </ul>
  </label>

  <label>
    Children
    <ul class="button-group button-click">
      <li><a href="#" class="small button secondary"><i class="fa fa-plus"><span class="hide">+</span></i></a>
      </li>
      <input type="text" class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" />
      <li><a href="#" class="small button secondary"><i class="fa fa-minus"><span class="hide">-</span></i></a>
      </li>
    </ul>
  </label>

  <label>
    Infants
    <ul class="button-group button-click">
      <li><a href="#" class="small button secondary"><i class="fa fa-plus"><span class="hide">+</span></i></a>
      </li>
      <input type="text" class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" />
      <li><a href="#" class="small button secondary"><i class="fa fa-minus"><span class="hide">-</span></i></a>
      </li>
    </ul>
  </label>
</body>
</html>

Answer №1

You can create separate handlers for the plus and minus buttons to update input values using the 'this' keyword.

$(function() {
  registerEvents();
});

function registerEvents(){
  $('.button-group .fa-plus').on('click', function(){
    var input = $(this).closest('li').next()
    input.val(+input.val() + 1);
    updateTravellerCount();
    return false;
  })
  $('.button-group .fa-minus').on('click', function(){
    var input = $(this).closest('li').prev()
    var val = +input.val() > 0 ? +input.val() - 1 : 0
    input.val(val);
    updateTravellerCount();
    return false;
  });
}

function updateTravellerCount(){
  var total = 0;
  $.each($('.button-group input'), function(){
    total += +$(this).val();
  });
  $('.main').val(total)
}
<html>
<head>
  <title>Input Number Incrementer</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>

<body>
  <label>
    Count all Travelers
    <input type="text" class="main" value="0" placeholder="" />
  </label>
  <br/>
  <br/>
  <label>
    Adults
    <ul class="button-group button-click">
      <li><a href="#" class="small button secondary"><i class="fa fa-plus"><span class="hide">+</span></i></a>
      </li>
      <input type="text" class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" />
      <li><a href="#" class="small button secondary"><i class="fa fa-minus"><span class="hide">-</span></i></a>
      </li>
    </ul>
  </label>

  <label>
    Children
    <ul class="button-group button-click">
      <li><a href="#" class="small button secondary"><i class="fa fa-plus"><span class="hide">+</span></i></a>
      </li>
      <input type="text" class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" />
      <li><a href="#" class="small button secondary"><i class="fa fa-minus"><span class="hide">-</span></i></a>
      </li>
    </ul>
  </label>


  <label>
    Infants
    <ul class="button-group button-click">
      <li><a href="#" class="small button secondary"><i class="fa fa-plus"><span class="hide">+</span></i></a>
      </li>
      <input type="text" class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" />
      <li><a href="#" class="small button secondary"><i class="fa fa-minus"><span class="hide">-</span></i></a>
      </li>
    </ul>
  </label>
</body>

</html>

I have attempted to make this more modular. It may not be perfect, but it could be useful. Check out the JSFiddle for reference.

Answer №2

The selector you are currently using is ".button-click a", however, it should be updated to ".button-click > a".

This change will specifically target an a element that is a direct child of an element with the button-click class.

Answer №3

I have implemented two unique classes for the anchor tags and organized the jQuery script to ensure clarity and simplicity.

Live Demo on Plnkr:

http://plnkr.co/edit/GqOeRWaaAq8BjeQSVDHc?p=preview

Code Snippet:

  $(function() {
  $(".button-click a").on("click", function() {

    var $button = $(this);
    var oldValue = $button.closest("ul").children('input').val();

    if ($button.hasClass('plus')) {
      
      var newVal = parseInt(oldValue) +1;

    } else {
      // Ensure value doesn't go below zero
      if (oldValue > 0) {
        var newVal = parseInt(oldValue - 1);
      } else {
        newVal = 0;
      }
    }
    $button.closest("ul").children('input').val(newVal)
    var total_value = 0;
    $(".cat_textbox").each(function(){
      total_value += parseInt($(this).val());
    });
    $(".main").val(total_value);
  })
});
<!DOCTYPE html>
<html>

  <head>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="771d060212050e374459475947">[email protected]</a>" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
  </head>

  <body>
    <label>
Count all1 Traveller(s)
      <input class="main" value="0" placeholder="" type="text" />
    </label>
    <br />
    <br />
    <label>
Adults
       <ul class="button-group button-click">
        <li>
          <a href="#" class="small button secondary plus">
            <i class="fa fa-plus">
              <span class="hide">+</span>
            </i>
          </a>
        </li>
        <input class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" type="text" />
        <li>
          <a href="#" class="small button secondary minus">
            <i class="fa fa-minus">
              <span class="hide">-</span>
            </i>
          </a>
        </li>
      </ul>
    </label>
    <label>
  Children 
         <ul class="button-group button-click">
        <li>
          <a href="#" class="small button secondary plus">
            <i class="fa fa-plus">
              <span class="hide">+</span>
            </i>
          </a>
        </li>
        <input class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" type="text" />
        <li>
          <a href="#" class="small button secondary minus">
            <i class="fa fa-minus">
              <span class="hide">-</span>
            </i>
          </a>
        </li>
      </ul>
    </label>
    <label>
   Infants  
         <ul class="button-group button-click">
        <li>
          <a href="#" class="small button secondary plus">
            <i class="fa fa-plus">
              <span class="hide">+</span>
            </i>
          </a>
        </li>
        <input class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" type="text" />
        <li>
          <a href="#" class="small button secondary minus">
            <i class="fa fa-minus">
              <span class="hide">-</span>
            </i>
          </a>
        </li>
      </ul>
    </label>
  </body>

</html>

Answer №4

Some outdated browsers might encounter difficulties with the <input type="number". You could consider utilizing a different approach, like the example below:

<html>
<head>
<title>Number Input Incrementer</title>
</head>
<body>
<label>
Count total Traveller(s)
<input type="text" class="main" value="0" placeholder="" />
</label>
<br/><br/>
<label>
Adults
 <ul class="button-group button-click">
  <li><a href="#" class="small button secondary"><i class="fa fa-plus"><span class="hide">+</span></i></a></li>
  <input type="text" class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" />
  <li><a href="#" class="small button secondary"><i class="fa fa-minus"><span class="hide">-</span></i></a></li>
  </ul>
  </label>
  
  <label>
  Children 
   <ul class="button-group button-click">
  <li><a href="#" class="small button secondary"><i class="fa fa-plus"><span class="hide">+</span></i></a></li>
   <input type="text" class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" />
  <li><a href="#" class="small button secondary"><i class="fa fa-minus"><span class="hide">-</span></i></a></li>
  </ul>
  </label>
  
  
    <label>
   Infants  
   <ul class="button-group button-click">
  <li><a href="#" class="small button secondary"><i class="fa fa-plus"><span class="hide">+</span></i></a></li>
   <input type="text" class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" />
  <li><a href="#" class="small button secondary"><i class="fa fa-minus"><span class="hide">-</span></i></a></li>
  </ul>
  </label>
  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  <script>
      $(function() {
  $(".button-click a").on("click", function() {

    var $button = $(this);
    var input  = $button.closest("ul").find("input");
    var oldValue = parseInt(input.val());
    var newVal = 0;
    var total_value = 0;

    if ($button.text() == "+") {
       newVal = parseInt(oldValue) +1;

    } else {
      // Ensure decrement does not go below zero
      if (oldValue > 0) {
         newVal = parseInt(oldValue - 1);
      } else {
        newVal = 0;
      }
    }

    $(input).val(newVal);
    
    $(".cat_textbox").each(function(){
       total_value += parseInt($(this).val());
    });

    $(".main").val(total_value);
  });
});
  </script>
  </body>

</html>

Answer №5

Give this a shot: I made a few modifications to your existing function.

$(function() {
   $(".button-click a").on("click", function() {
   var $button = $(this);
   var mainCounter=$('.main').val();
   var buttonText= $button.text();
   var oldValue=$button.closest("ul").children('input').val();
   var newValue=null;

   if(buttonText=='+'){
      newValue=parseInt(oldValue) +1;
      mainCounter=parseInt(mainCounter) +1;
   }else{
      newValue=parseInt(oldValue) -1;
      mainCounter=parseInt(mainCounter) -1;
   }

  $button.closest("ul").children('input').val(newValue);
  $('.main').val(mainCounter);
  });
});

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

The useEffect hook in ReactJs is triggering multiple times

Encountering challenges while developing an Infinite scroll using ReactJs and Intersection observer API. Upon initial application load, the API gets called twice instead of once. This behavior may be due to strict mode, although not confirmed. Additionall ...

What is the best way to showcase an item from an array using a timer?

I'm currently working on a music app and I have a specific requirement to showcase content from an array object based on a start and duration time. Here's a sample of the data structure: [ { id: 1, content: 'hello how are you', start: 0 ...

Tips on serializing two arrays into JSON format and incorporating them in an AJAX request

I have a task where I need to retrieve all the names and details associated with a specific reference number. To accomplish this, I am using a while loop. However, I am unsure of how to encode these values in JSON format so that I can use them in AJAX for ...

Send data from JavaScript variables to PHP script

I've been trying to figure out how to pass variables from a js function to my database using php, but I've hit a roadblock. Any suggestions on how I can resolve this issue would be greatly appreciated. <html xmlns="http://www.w3.org/1999/xhtm ...

React function does not provide a return value

In my function, I am calculating the current sum of elements. Within my Api, there is a method called Getcoin that works correctly when I log each element during the foreach cycle. However, I am not getting any results in the return statement or console.lo ...

Expression Engine presents a dilemma with breadcrumbsOr:Expression Engine

Having a slight issue with Expression Engine. I've created a breadcrumb snippet using {if segment_} coding. While setting up if rules for each page on the small site, I encountered a problem with one of the breadcrumb trials. The issue arises when tr ...

Finding the next div by its ID using jQuery

Currently, the jQuery code provided only allows navigation from the Sport section to the Entertainment section. Is there a way to create a script that allows navigation between any div sections with just one piece of code? <div id="topBar"> &l ...

Transfer a data element to a PHP webpage and launch the said webpage in a fresh browser tab

Here's an example of some code I'm working with: $(document).on('click', '#button', function(){ var my_info = 'Example Example Exam'; $.ajax({ type: "POST", url: "view.php", data: "my_info ...

AngularJS: Patience for an asynchronous request

I'm having trouble understanding the concept of promises in AngularJS. Here is a provider I have: var packingProvider = angular.module('packingProvider',[]); packingProvider.provider('packingProvider',function(){ ...

Sending the most recent result to each dynamically created div

In my WordPress project, I have an event panel that displays upcoming event details and shows the remaining time until the next event. The countdown dynamically gets values from the database and calculates the time left based on the user's input in th ...

Using jQuery to dynamically populate input values within a table that contains multiple rows with text from their respective siblings

My table contains many columns (exact number varies). $('.action-checkbox').val( $(this).parent().parent().find(".col-record_id").first().text().trim() ) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery ...

What is V8's approach to managing dictionaries?

After attending V8 presentations, it became clear to me that it optimizes constructions such as the one below by tagging a type object: function Point(x, y) { this.x = x; this.y = y; } I am curious about what happens if I were to return an object (JS ...

How to arrange data in angular/typescript in either ascending or descending order based on object key

Hey there! I'm fairly new to Angular and have been working on developing a COVID-19 app using Angular. This app consists of two main components - the State component and the District component. The State component displays a table listing all states, ...

Struggling to access FormData in php

I'm having trouble retrieving variables from FormData in PHP after making an AJAX call. What could be causing this issue? Here is the snippet of my JavaScript code: var sendData = new FormData(); sendData.append('itemid',$('select#sel ...

Turn off HTML display for Internet Explorer users

I am looking to implement code that will block certain pages for Internet Explorer users, making it accessible only for Google Chrome and Firefox users. Do you have any suggestions on how I can achieve this or if there are existing solutions available? I& ...

Displaying the Yii form directly on the page upon loading, rather than enclosed within a jQuery dialog box

After studying this yii wiki page, I encountered an issue where the form is supposed to appear within a jQuery dialog box, but it opens immediately when the page loads instead. Upon further investigation, I discovered that removing the success callback fr ...

Customize CKEditor by automatically changing the font family when the page is loaded

How can I change the font-family of CKEditor to Meiryo based on a JavaScript boolean? I attempted this code in my custom JS within an if condition, but it did not successfully change the font-family: config.font_style = { element : 'span&apo ...

example of using relative jquery countdown.js

I've been attempting to grasp JavaScript and incorporate the countdown found at this link (specifically, the example with a 300-second countdown), but after spending a few hours on it, I haven't been able to get it functioning properly. I have c ...

FullCalendar is encountering loading issues when trying to fetch data from JSON, with the

I am currently utilizing FullCalendar to create a schedule for theater rehearsals. After considering my options, I concluded that JSON would be the most efficient way to retrieve events from my MySQL database. In the JavaScript code for the calendar page, ...

The alignment of the table appears off on Internet Explorer, while it is perfectly centered on all other web

I'm encountering a strange issue with my table alignment on Internet Explorer. The table is offset to the right in IE, but perfectly centered in other browsers like Edge, Firefox, and mobile browsers. I am using Bootstrap for my design, but haven&apos ...