Does selecting a checkbox activate just one field?

I'm in the process of creating a form that includes a number input field attached to each checkbox, which should only appear when the checkbox is selected. Here's what I have so far:

  <!-- Option1 -->
                      <div class="form-row">
                        <div class="form-group col-md-8">
                          <div class="form-check">
                            <input class="form-check-input showman" type="checkbox" onchange="showqt()" value="Button Chicken Amritsari" id="c1">
                            <label class="form-check-label" for="c1">
                              Button Chicken Amritsari<i><br>(Boneless) Serves 2<br>INR 290</i>
                            </label>
                          </div>
                        </div>
                          <div class="form-group col-md-4 " id="ifYes" style="display: none; float:right;">
                            <!-- <label for="qtcounter">Quantity:</label> -->
                            <div class="input-group" id="qtcounter">
                              <input type="button" value="-" class="button-minus" data-field="quantity">
                              <input type="number" step="1" max="" value="1" name="quantity" class="quantity-field">
                              <input type="button" value="+" class="button-plus" data-field="quantity">
                            </div>
                          </div>
                      </div>
                      <!-- Option 1 ends -->
and more unique text would be inserted here

Is there a way to handle this globally or do I need to write specific JavaScript for each checkbox?

Answer №1

     <!-- Option1 -->
                          <div class="form-row">
                            <div class="form-group col-md-8">
                              <div class="form-check">
                                <input class="form-check-input showman" type="checkbox" onchange="showqt(this)" value="Button Chicken Amritsari" id="c1">
                                <label class="form-check-label" for="c1">
                                  Button Chicken Amritsari<i><br>(Boneless) Serves 2<br>INR 290</i>
                                </label>
                              </div>
                            </div>
                              <div class="form-group col-md-4 " id="ifYes" style="display: none; float:right;">
                                <!-- <label for="qtcounter">Quantity:</label> -->
                                <div class="input-group" id="qtcounter">
                                  <input type="button" value="-" class="button-minus" data-field="quantity">
                                  <input type="number" step="1" max="" value="1" name="quantity" class="quantity-field">
                                  <input type="button" value="+" class="button-plus" data-field="quantity">
                                </div>
                              </div>
                          </div>
                          <!-- Option 1 ends -->
                          <div class="form-row">
                            <div class="form-group col-md-8">
                              <div class="form-check">
                                <input class="form-check-input showman" type="checkbox" onchange="showqt(this)" value="Chicken Korma Awadhi" id="c2">
                                <label class="form-check-label" for="c2">
                                  Chicken Korma Awadhi<br><i> (Boneless) Serves 2<br>INR 290</i>
                                </label>
                              </div>
                            </div>
                              <div class="form-group col-md-4" id="ifYes" style="display: none; float:right;">
                                <!-- <label for="qtcounter">Quantity:</label> -->
                                <div class="input-group" id="qtcounter">
                                  <input type="button" value="-" class="button-minus" data-field="quantity">
                                  <input type="number" step="1" max="" value="1" name="quantity" class="quantity-field">
                                  <input type="button" value="+" class="button-plus" data-field="quantity">
                                </div>
                              </div>
                          </div>

function showqt(obj){
    if ($(obj).is(":checked")) {
      
      jQuery(obj).parents(".form-row").find("#ifYes").show();
    }
    else {
        jQuery(obj).parents(".form-row").find("#ifYes").hide();
    }
  }

Phew, it's all set now!

Answer №2

Instead of complicating things, stick with the simplicity of using jQuery:

$('#ifYes').show(); and $('#ifYes').hide();

Answer №3

To achieve this effect using only CSS, you can utilize the :checked pseudo-selector in combination with the ~ general sibling combinator. This will allow you to toggle the visibility of the counter dynamically.

.form-row {
  padding-top: 1rem;
}
.counter {
  display: none;
 }
.showman:checked ~ .counter{
  display: block;
}
<!-- Option1 -->
<div class="form-row">

    <input class="form-check-input showman" type="checkbox" value="Button Chicken Amritsari" id="c1">
    <label class="form-check-label" for="c1">
      Button Chicken Amritsari<i><br>(Boneless) Serves 2<br>INR 290</i>
    </label>
    
  <div class="counter">
    <input type="button" value="-" class="button-minus" data-field="quantity">
    <input type="number" step="1" max="" value="1" name="quantity" class="quantity-field">
    <input type="button" value="+" class="button-plus" data-field="quantity">
  </div>
</div>
<!-- Option 1 ends -->

<div class="form-row">

    <input class="form-check-input showman" type="checkbox" value="Chicken Korma Awadhi" id="c2">
    <label class="form-check-label" for="c2">
      Chicken Korma Awadhi<br><i> (Boneless) Serves 2<br>INR 290</i>
    </label>

  <div class="counter">
    <input type="button" value="-" class="button-minus" data-field="quantity">
    <input type="number" step="1" max="" value="1" name="quantity" class="quantity-field">
    <input type="button" value="+" class="button-plus" data-field="quantity">
  </div>
</div>

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 fade effect on an element cannot be achieved using setTimeout

I'm trying to call a tooltip and hide it after 9 seconds, but for some reason, it's not working as expected. The issue I'm facing is that the "tooltip" only hides after it initially loads. It doesn't respond when I click on the "Touch ...

jquery combobox with overlapping autocomplete suggestions

Encountering an issue with the jquery autocomplete combobox where they overlap when positioned side by side. Referencing this link for guidance: http://jqueryui.com/autocomplete/#combobox <!doctype html> <html lang="en"> <head> <me ...

Guide to making a basic cross-domain ajax request that fetches an HTML webpage

I have been researching various methods for making cross domain calls using ajax, but they all seem overly complex or too specific. Below is a basic HTML page where I am trying to send request parameters to a specific JSP on my server. <!DOCTYPE html&g ...

Create an array containing key-value pairs where the values are objects

I've been struggling to create a specific data structure in Javascript and I could really use some guidance: [arrayValue: {objectKey: objectValue}, arrayValue2: {objectKey: objectValue}] Here's what I've attempted so far: var arr = []; var ...

React: The getDerivedStateFromProps method does not allow the invocation of functions

I can't seem to figure out why I keep getting a TypeError - Cannot read property 'getTodosList' of null when trying to call the getTodosList function inside the getDerivedStateFromProps method. Furthermore, after implementing the getDerived ...

Prevent Sending Blank Forms with Stripe js

Currently, I am working on a solution to prevent users from submitting the stripe form when certain inputs are left empty. To achieve this, I have integrated stripe.js elements into my form and implemented the form submission handling within my vue compone ...

Node-flickrapi utilizes the Flickr API Oauth to cache the oauth_verifier for authentication

I've been having a great experience using the authenticated Flickr API with Oauth and successfully implemented it with node.js thanks to the node-flickrapi NPM package. Whenever I run my code, the console prompts me to - add the following variables ...

Exporting the default object scope in Vue.js allows for easy sharing

Could someone please clarify the usage of export default in Vue files? Appreciate it. For example: HelloWorld.vue <template> <div id="app"> <HelloWorld /> </div> </template> <script> import HelloWor ...

Mistakenly appearing at the top of the window instead of the bottom of the window

Utilizing Vue.js to fetch resources from a Laravel API periodically and paginate(), after retrieving the initial 10 instances, I aim to get the next 10. Here's how my method looks: scroll () { window.onscroll = () => { let bottomOf ...

What is the best way to eliminate the [lang tag] from a URL in Next.js?

I am looking to eliminate either the /en or the /it from the URL without explicitly adding it. i18next seems to be doing it automatically, and I am unsure how to disable this behavior. I simply want it to happen in the background. https://i.stack.imgur.co ...

Fixing the GLTF Loader Error in Vue JS: Troubleshooting the issue of 'No loaders configured'

I am attempting to integrate a gltf file into a Vue project. Below is the code I have been working on: import * as THREE from 'three' import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'; let scene, camera, renderer; fu ...

I often find myself yearning for the good old days of prototyping functions when initializing a new

I just created a module in nodejs called Test.js with the following code: function Test() { this.key = 'value'; } Test.prototype.foo = function () { return 'foo'; } module.exports = Test; Then, in B.js file: var Test = require(&a ...

How can we use response.render in Express.js to render HTML on the client side?

I have set up a simple Express.js application with the following routes: router.get('/', function(req, res){ res.render('login'); }); Everything is working fine - when I log into the main page on my localhost, the HTML fro ...

Vuetify's V-alert component doesn't seem to close properly when the value property is updated, as it only displays the

I have a v-alert component that appears and disappears based on a Vuex store - it shows an error message and clears it after 4s! Below is the code for my V-alert component: The issue I am facing is that the :value attribute does not work when the value o ...

Leveraging Next.js to efficiently handle multiple asynchronous requests with NextResponse

I have developed a login/signup application using NextJS. When attempting to log in, the logic in my route.ts file sends requests to a MongoDB database to check if the user exists and if the password is correct. However, instead of receiving the expected 4 ...

Is AjaxMin's EvalTreatment changing the game for JavaScript minification?

While minifying my project using the AjaxMin.dll with the default settings on every build/deployment, I ran into a problem. One of our third-party JavaScript files contains an eval statement that references variables or parameters which, when minified, cau ...

In JavaScript, the price can be calculated and displayed instantly when a number is entered into a form using the input type 'number'

Is there a way for me to automatically calculate the price and display it as soon as I enter a number into my form? Currently, the price is only displayed after I press submit. <script type="text/javascript"> function calculatePrice() { ...

Ways to trigger a JavaScript notification

I consider myself experienced in scripting, but I can't seem to figure this out. I'm trying to trigger a function on a button click event, so I decided to start by testing the buttonclick event with a basic window.alert. I wrote the following htm ...

Add a parameter within a loop using JavaScript

I am currently working on a function with a parameter called menu. removeChildCheck:function(menu){ let removeArrayValues = []; for(var i=0; i < this.checkbox.menu.length; i++){ removeArrayValues.push(this.checkbox.menu[i].value); ...

Issue with Ajax form submission functionality not working for sending form data

I recently found the solution to executing a Send Mail script without reloading the page after facing some AJAX issues. However, I am now encountering a problem where the post data is not being received by the PHP script when my form posts to AJAX. For re ...