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

Tips for effectively making REST requests from a ReactJS + Redux application?

I'm currently working on a project using ReactJS and Redux, incorporating Express and Webpack as well. I have successfully set up an API and now need to figure out how to perform CRUD operations (GET, POST, PUT, DELETE) from the client-side. Could so ...

Exploring the Power of Websharper with Sitelets and Forms

I have been working on developing a form using Websharper to gather user input. Currently, I have identified three actions for my website: type MyAction = | [<CompiledName "">] Index | [<Method "POST">] GetUser of username : string ...

Error occurs when using jQuery.ajax on mobile devices such as android or ios

When accessing my website, an ajax request is made to my REST API. It works perfectly on desktop browsers like Chrome, Internet Explorer, and Firefox, as well as on my Windows phone. However, when trying to access it from an Android or iOS device, the XHR ...

Load specific data using jQuery's ajax method

Looking to dynamically change the text of a div based on content from another page that pulls data from a database. Specifically, I have a URL "Ajax/popup.aspx?pID=23" which returns a simple HTML file with an h2 and some text. I plan to use .load function ...

Implementing Flash Messages with jQuery AJAX for Every Click Event

I've been working on integrating Ajax and PHP, successfully fetching data from the database. However, I'm facing an issue where the Ajax response is only displayed in the HTML for the first click. What I actually want is to show a "success/error" ...

Is there a way to access the data attribute value from one component in another component without relying on an event bus mechanism?

In the 'App.vue' component, there is a data attribute called 'auth' that indicates whether the user is logged in. If it is empty, the user is not logged in; if it contains 'loggedin', then the user is authenticated. Now, let& ...

Issue with clearTimeout function not functioning properly on keyup event in iFrame

While there may be many similar questions out there, I have yet to find a solution that works for me. Currently, I am developing a WYSIWYG editor and I want it to save when the user performs a keyup action. However, I do not want it to update after every ...

Ways to retrieve Data obtained in response using superagent

I am currently working on hitting an API and extracting the data received in response. To achieve this, I am utilizing superagent to retrieve the data from the API. I have inspected my network tab, however, I am encountering an issue where I want to extra ...

Identifying the accurate folder for file uploads

In my project directory, I have a folder named uploads, along with two files called upload.html and upload.php. The relevant part of my upload.html file looks like this: $(document).ready(function(){ $("#pictureUploadSubmit").submit(function(event) { ...

HTML form for selecting shipping method in PayPal

In my shopping cart setup, I offer two shipping methods: 'express' and 'standard'. I'm wondering if it's feasible to transmit this data to PayPal using HTML variables? ...

Bootstrap modal not displaying in full view

I recently ran into some issues while using a jQuery plugin with my bootstrap modal on my website. After implementing jQuery.noConflict(), I encountered a problem where the program no longer recognized $, forcing me to replace all instances of it with jQue ...

Is there a way to retrieve all documents based on the start and end of a specific day?

One common issue I am facing involves submitting a date to my nodejs server in a specific format

 2018-11-02T00:36:00+05:30 // The actual time should be 12:36AM However, when examining the document in my database (using studio 3T), the format appear ...

What is the best way to show a message next to a text box in a form?

I have a form called test.php with two buttons for entering an email ID and user ID, as well as a submit button. Upon clicking the submit button, my code checks if the email ID exists and displays a message to the user. I want to show this message next to ...

What is the best way to incorporate a changing variable within an htmx request?

One of the endpoints in my site requires an ID to be passed as a parameter. For example: mysite.com/product/{id}?limit=5 I'm wondering how to pass the 'id' variable in the hx-get attribute. I can utilize AlpineJS or vanilla JS for this tas ...

Vue click event does not function when used with an anchor tag containing an href attribute

Looking for a way to create an anchor tag that executes a click handler instead of following the href attribute when clicked. Currently working with Vue 1 and my code is as follows: <div v-if="!hasPage(category.code)"> <div> <templat ...

The use of "app.use("*") appears to be triggering the function repeatedly

app.use("*", topUsers) is being invoked multiple times. The function topUsers is called repeatedly. function topUsers(req, res, next){ console.log("req.url", req.url) findMostUsefullReviewsAggregate(6) .then(function(aggregationResult){ ...

Disabling the close button on a particular Colorbox popup

Utilizing the colorbox plugin to showcase messages on my website, one of them being a "wait for response" message that I wish to prevent users from closing themselves. Although I'm able to unbind the ESC key and disable overlay close options, I still ...

Is it possible to adjust the dimensions of the number input spinner?

When working with a number input that includes a spinner, I have encountered challenges in changing the size of the spinner itself. Specifically, I am referring to the <input type='number'> element. Despite my efforts to adjust its size thr ...

Obtain URL parameters prior to rendering with Next.js on the server side

Looking to retrieve the parameters from a URL coming from the Spotify API, for example: http//link.com/?code=examplecode. Is there a way to extract the value of "code" prior to rendering so that I can redirect it and transfer the code value to another p ...

Tips on sending asynchronous requests to a PHP page using jQuery AJAX

As a newcomer to web development, I am working on creating a social networking website for a college project. One feature I want to implement is updating the message count in the menu every time there is a new message in the database for the user (similar ...