JavaScript function that automatically updates a text field when a radio button is selected and a button is pressed

I need assistance with updating the quantity value when a radio button is selected. The default value of the quantity should be 1, but when I try to increase it by clicking on the addToOrderBtn, it resets back to 1.

After selecting a radio button, it should update a textfield that displays the quantity. Subsequently, I have a button to add items to the order. However, each time I attempt to modify the quantity in the textfield, it reverts back to the default value of 1.

In addition, the textfield tracking Total items (totalItems) should accumulate the input from addNumberOfItems.

I've tried updating the value of addNumberOfItems upon button click, yet it remains at the default value.

Please provide JavaScript-based solutions only.

Thank you!

Code pen: http://codepen.io/anon/pen/LpJqgj

        var addNumberOfItems = document.getElementById("numberOfItems");
        var addToOrderBtn = document.getElementById("addToOrder");
        var totalItems = document.getElementById("items");
        var totalPrice = document.getElementById("total");


    if (selected == "Classic" && foodOptionChecked1 == true) {
        addNumberOfItems.value = 1;
    };


    addToOrderBtn.onclick = function() {

        document.getElementById('numberOfItems').value = addNumberOfItems.value;

        totalItems.value = addNumberOfItems.value;
        totalPrice.value = foodClassic[0].smallPrice;

        addNumberOfItems.value = "";

    };

HTML

  <fieldset class="form1 hide" id="choices">
  <legend> your Choices </legend>

   <p style="margin-left:25%">Which one would you like?</p>

  <form style="float: right" id="selectSize">

    <input type="radio" id="food1" name="size" value=""><label id="foodLabel1">food1</label> 
    <br>
    <input type="radio" id="food2" name="size" value=""><label id="foodLabel2">food2</label>
    <br>
    <input type="radio" id="food3" name="size" value=""><label id="foodLabel3">food3</label>
    <br>
    <input type="radio" id="food4" name="size" value=""><label id="foodLabel4">food4</label>


     <input type="text"  id="numberOfItems" name="" value="">

   <button type="button" id="addToOrder">Add to order</button>
   <button type="button">Remove last item</button>

  </form>
  <p style="margin-top: 15%; margin-left:25%"> Extras! </p>
  <p style="margin-top: 11%; margin-left:25%"> How many? </p>

  </fieldset>

      <fieldset class="form1 hide" id="orderStatus">
      <legend> Order Status </legend>

       <form>
        Items<input type="text" name="" id="items">
        Total<input type="text" name="" id="total">

        <button type="button">Order Now</button>
        <button type="button">Cancel</button>
      </form>
     </fieldset>

Answer №1

One reason for this behavior is that within the getOrder() function, the line addNumberOfItems.value = 1; sets the quantity to 1 whenever the quantity value is changed.

To resolve this issue, consider adding the following code snippet to your getOrder() function to ensure the default value is maintained:

if (selected == "Classic" && foodOptionChecked1 == true) {
          if(addNumberOfItems.value.length == 0)  
             addNumberOfItems.value = 1;
            }
        };

Despite implementing the above solution, it appears that the main.js file may contain some code that triggers the getOrder() function after the quantity is modified, causing the reset problem.

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 function Geometry.center() has not been used

Within my code, I am working with a BufferGeometry that undergoes changes in vertices and colors periodically. To manage this, I create a new buffergeometry if more space is required for vertices; otherwise, I reuse the existing one by adjusting its drawRa ...

Setting the height of a Bootstrap radio button

My Bootstrap radio buttons are set to a width of 200px. However, when the text inside the button exceeds this width, it wraps onto two lines leading to changes in button height. How can I ensure that all other buttons displayed scale to the same height? h ...

`Finding and including the additional object in JavaScript`

Seeking guidance on how to manipulate a specific object in Javascript, I have successfully retrieved the object based on a filter, but I am unsure how to append `'in'='bank' and 'out'='bank'` of non-filtered ids to ...

React Hook Form – Difficulties with error handling when utilizing multiple forms simultaneously in react hook form version 7.5.2

Previously, in the earlier versions of react hook form, multiple forms could function if another form object was created using the following code: const { register: register2, handleSubmit: handleSubmit2, errors: errors2 } = useForm() H ...

Strangely odd actions from a JavaScript timepiece

After answering a question, I encountered a problem with my JavaScript clock that displays the day, time, and date on three lines. To make sure these lines have the same width, I used the BigText plugin, which works well except for one issue. tday=new A ...

What advantages does utilizing NPM provide compared to directly incorporating the JavaScript library into an MVC project?

When working on an MVC project, I experimented with two different methods of including jQuery: I first downloaded the jQuery files and manually added them to the project, as shown here: https://i.sstatic.net/2TjqX.png I also tried using the bundle sett ...

Pass the extended object from the service to the controller within a promise using the .map function

section: I am currently working on extending a JSON object within a service and passing it to a controller. The JSON originally came to the service from another service that makes backend calls. The code is quite intricate, so I've added comments an ...

Transform my sidebar menu into buttons for mobile and smaller screens

As a newcomer to bootstrap, I've been experimenting with converting my sidebar into a button for smaller screen sizes. I've managed to customize everything to fit my needs except for one thing. When the screen size is reduced (as on mobile devic ...

The attempt to test the AngularJS application using the Jasmine plugin was unsuccessful

I'm currently in the process of learning how to write test cases for my angularJS application. As a beginner, I'm searching for some sample examples of working demos. I came across an example online that uses the Jasmine plugin to test an angular ...

Encountered issues with installing Phoenix Framework npm dependencies (phoenix & phoenix_html) during Travis CI setup

I recently encountered an issue while testing my Phoenix Framework project with Travis CI. Initially, everything was running smoothly with only Elixir tests. However, when I attempted to add some JavaScript tests, I ran into a roadblock. The problem stemm ...

Transmit intricate data structure to a web API endpoint using AJAX requests

When attempting to send a complex object named vm containing an object 'Budget' and an array 'BudgetDetails' populated with rows from an HTML table to my API controller using AJAX, I encounter the error message "Uncaught RangeError: Max ...

How to retrieve an object of type T from a collection of classes that extend a common base type in Typescript

In my current project, I have a class named Foo that is responsible for holding a list of items. These items all inherit from a base type called IBar. The list can potentially have any number of items. One challenge I am facing is creating a get method in ...

Printing directly from a webpage

Can a webpage send a print command without relying on the keyboard shortcut Ctrl + P? I vaguely recall hearing that JavaScript is unable to access the printer directly to initiate a print without using the key combination. ...

Troubleshooting issue: AJAX causing JavaScript form validation to fail

I'm having trouble with form validation using JavaScript + AJAX. It doesn't seem to be working properly. Could someone please help me figure out what I'm doing wrong? function validateform() { $.ajax({ url: '../api?type=vali ...

Tips for eliminating the white border in a stacked column Google chart

Is there a way to eliminate the white border in a stacked column google chart? If anyone has any tips or suggestions, please share! Here is an example of what I am referring to: my current chart ...

The reliability of jQuery keydown events can vary

When I press the ESC key, I am trying to find the href attribute of a link and redirect to that. The code I am using works, but it's inconsistent and I can't figure out why. If the cursor is in an input field on the page and I press the ESC key, ...

Guide to Positioning Pre-Loader in the Center on Mobile Devices

Despite trying numerous solutions, I'm struggling to center my pre-loader on mobile devices. It looks fine on desktop and mobile landscape orientations, but whenever I switch to mobile portrait, it just won't center properly. CSS: .load ...

Issue encountered in React 18: The value on the left side of an assignment statement must be a variable or a property that can be accessed

After upgrading my React version from 17 to 18, I encountered an error with this code: data?.area?.width=['111','220']. The error message states "The left-hand side of an assignment expression must be a variable or a property access." W ...

Is it possible to transfer data from a form to a block without needing to reload the entire page

Trying to figure out a way to transfer data from a form and save it to the database simultaneously on a single page. I am not quite sure how to accomplish this, but here is the code snippet that I have created: $("#formbutton").click(function(event) { ...

Performance.now() and its interaction with the toFixed() method

When you apply toFixed to performance.now, it displays a specific number of digits that may not be rounded as expected. Interestingly, the number of digits can vary based on the platform used. For instance, in Chrome (v87.0.4280.66), it can show up to 35 ...